laravel AngularJS:在用户身份验证后重新加载 ng-include(或解决问题的更好方法)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19203777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:31:19  来源:igfitidea点击:

AngularJS: Reload ng-include after user authentication (or a better way to solve issue)

angularjslaravellaravel-4

提问by Jazzy

I am really just learning Angular and I am attempting to create an app that limits content access based on authentication. I have the authentication part working (also using the Laravel PHP framework), but I am having an issue "reloading" certain pieces of content based on auth status, namely after a successful authentication.

我真的只是在学习 Angular,我正在尝试创建一个基于身份验证限制内容访问的应用程序。我的身份验证部分正在工作(也使用 Laravel PHP 框架),但是我遇到了一个问题,即根据身份验证状态“重新加载”某些内容,即在成功身份验证之后。

Initially, what I am trying to do is update the main navigation menu after a user logs in. I am sure there is a better approach, but what I have so far is a view returned from the server that has different navigation elements depending on whether the user is logged in or not, then loading that into an element with ng-include.

最初,我想做的是在用户登录后更新主导航菜单。我确信有更好的方法,但到目前为止我所拥有的是从服务器返回的视图,该视图具有不同的导航元素,具体取决于用户是否登录,然后使用 ng-include 将其加载到元素中。

There is an option to log in, which loads a login form into the ng-view. After the user logs in, I would like to refresh the ng-include with the view from the server.

有一个登录选项,它将登录表单加载到 ng-view 中。用户登录后,我想用来自服务器的视图刷新 ng-include。

Is there a way to reload that template in the ng-include after a successful login?

成功登录后,有没有办法在 ng-include 中重新加载该模板?

Please feel free to recommend a better technique to solving this if this is the wrong approach. Of course, this would be very easy to do in jQuery, but I would prefer to do things the Angular way.

如果这是错误的方法,请随时推荐更好的技术来解决这个问题。当然,这在 jQuery 中很容易做到,但我更喜欢用 Angular 的方式做事。

Here is some of my code so far:

到目前为止,这是我的一些代码:

index.html:

索引.html:

<div class="container" ng-controller="appController">

    <div id="nav" ng-include src="menuUrl()"></div>

    <div class="row">
        <div class="span3" ng-include src="'partials/brands.html'" ng-controller="brandController"></div>
        <div class="span9" ng-view></div>
    </div>

</div>

Some controllers:

一些控制器:

.controller('appController', function($scope){
    $scope.loggedIn = false;

    $scope.menuUrl = function() {
        return "partials/nav.html";
    };

})
.controller('loginController',function($scope, $sanitize, $location, Authenticate, Flash){
    $scope.login = function(){
        Authenticate.save({
            'email': $sanitize($scope.email),
            'password': $sanitize($scope.password)
        },function() {
            $location.path('/products')
            Flash.clear()
            sessionStorage.authenticated = true;
        },function(response){
            Flash.show(response.flash)
        })
    }
})
.controller('logoutController',function($scope, $location, Authenticate, Flash){
    $scope.logout = function (){
        Authenticate.get({},function(response){
            delete sessionStorage.authenticated
            Flash.show(response.flash)
            $location.path('/login')
        })
    }
})

Services:

服务:

.factory('Authenticate', function($resource){
    return $resource("/service/authenticate/")
})
.factory('Flash', function($rootScope){
    return {
        show: function(message){
            $rootScope.flash = message
        },
        clear: function(){
            $rootScope.flash = ""
        }
    }
})

App:

应用程序:

 .config(['$routeProvider',function($routeProvider){
        $routeProvider.when('/', {
            templateUrl: 'partials/home.html', 
            controller: 'homeController'
        })

        $routeProvider.when('/login', {
            templateUrl: 'partials/login.html', 
            controller: 'loginController'
        })

        $routeProvider.when('/logout', {
            templateUrl: 'partials/logout.html', 
            controller: 'logoutController'
        })

        $routeProvider.otherwise({redirectTo :'/'})
    }])
    .config(function($httpProvider){

        var interceptor = function($rootScope,$location,$q,Flash){

        var success = function(response){
            return response
        }

        var error = function(response){
            if (response.status == 401){
                delete sessionStorage.authenticated
                $location.path('/')
                Flash.show(response.data.flash)

            }
            return $q.reject(response)

        }
            return function(promise){
                return promise.then(success, error)
            }
        }
        $httpProvider.responseInterceptors.push(interceptor)
    })
    .run(function($http,CSRF_TOKEN){
        $http.defaults.headers.common['csrf_token'] = CSRF_TOKEN;
    })

Laravel view:

Laravel 视图:

<ul class="nav nav-tabs">
  <li><a href="#/">Home...</a></li>
  @if(!Auth::check())
  <li><a href="#/login">Log-in</a></li>
  @else
  <li><a href="#/logout">Log-out</a></li>
  @endif
  <li><input name="search" id="search" type="search" placeholder="Search products..." />
</ul>

采纳答案by Chandermani

You can start with raising an event when user login is success on the rootscope using broadcast method

当用户在 rootscope 上成功登录时,您可以使用广播方法开始引发事件

$rootScope.$broadcast('userLoggedIn',{user:user});

On the appControlleryou can subscribe to the even

appController你可以订阅甚至

$scope.$on("userLoggedIn",function(event,args) {
     $scope.menuUrl=null;
     $scope.menuUrl="partials/nav.html";
});

this also implies that change your menuUrl to a property in you controller and html binding.

这也意味着将您的 menuUrl 更改为控制器和 html 绑定中的属性。

Alos, if you can define multiple server views for logged in and anonymous user, then you can just flip the view on user login.

Alos,如果您可以为登录和匿名用户定义多个服务器视图,那么您可以在用户登录时翻转视图。

回答by Housne

@Chandermani 's answer is almost close, in fact, you can just add some random params to force refresh, just like this:

@Chandermani 的回答几乎接近,事实上,你可以添加一些随机参数来强制刷新,就像这样:

app.controller('appController', function($scope){
   var getMenu = function(){
     var random = Math.random();
     return "partials/nav.html?r=" + random;
   }
   $scope.menuUrl = getMenu();
   $scope.$on('userLoggedIn', function(){
     $scope.menuUrl = getMenu();
   })
})