2015-09-25 38 views
1

我有一個應用程序,前端在AngularJS上構建,後端在laravel 5.1上。

用戶認證是由賬戶控制器經由API調用來完成:

myApp.controller('LoginCtrl', function($scope,$auth,$location){ 

     $scope.authenticate = function(provider){ 
      $auth.authenticate(provider) 
      .then(function() { 
        toastr.success('You have successfully signed in with ' + provider); 
        $location.path('/'); 
       }) 
       .catch(function(response) { 
        toastr.error(response.data.message); 
       }); 
      }; 

}); 


angular.module('MyApp') 
    .factory('Account', function($http){ 
     return { 
      getProfile: function(){ 
       return $http.get('/api/me'); 
      } 
     } 
    }); 

一旦被認證,則該函數getProfile被稱爲由控制器向用戶數據填充到視圖:

myApp.controller('UserApiCtrl', function($scope,$auth,Account){ 
    $scope.user = {}; 
    $scope.getProfile = function(){ 
     Account.getProfile() 
      .then(function(response){ 

       $scope.user = response.data; 
      }) 

      .catch(function(response){ 

      }) 
    }; 

    $scope.getProfile(); 
}) 

對於該頁面能夠在所有不同的控制器上呈現用戶數據,我應該只爲$scope分配用戶數據,或將其分配給app.js中的$rootScope,其中用戶數據將在全球範圍內可用。

+4

使用'$ rootScope'存儲「全局變量」是一種主要的代碼異味。您應該使用注入每個需要數據的控制器的服務。由於服務是單例,所以每個注入點都會收到相同的數據實例。 – Claies

回答

0

你可以使用$cookies ("Provides read/write access to browser's cookies.")

myApp.controller('UserApiCtrl', function($scope,$auth,Account,Auth,$cookies){ 
     $scope.user = {}; 
     $scope.getProfile = function(){ 
      Account.getProfile() 
       .then(function(response){ 
        $cookies.putObject('user', response.data); 
       }) 

       .catch(function(response){ 
        if(response.status === 401) 
         $cookies.remove('user'); 
       }) 
     }; 

     $scope.getProfile(); 
    }) 
  • 示例服務:

    myApp.factory('Auth', ['$rootScope', '$cookies', function($rootScope, $cookies) { 
         $rootScope.user = $cookies.getObject('user') || { 
          id: '', 
          token: '' 
         }; 
    

    ...

0

我用控制器在我身上的標籤提供訪問更多的全球性東西,然後是控制器我個人的觀點是要做更具體的觀點。

<body ng-controller = "appController as app"> 
<div ui-view></div> 
</body> 

這似乎比使用$ rootScope更清潔。

相關問題