我的这段代码大部分都在工作,但我很难看到更改从控制器中的用户对象传播。
我想要做的是建立一个单一的User
服务来管理我网站上当前用户的所有方面。例如:User.login()
, User.logout()
, User.currentUser
,User.isLoggedIn
等。
请记住,我对 Angular 和 ngResource 还比较陌生 :-)。
- 有没有更好/更 Angular 的方式来构建它?
- $resource 工厂上的自定义属性甚至可能吗?
感觉好像我
$rootScope.$apply()
在这里需要一个或类似的?/** * The $resource factory. */ angular.module('myApp.services', ['ngResource']) .factory('User', ['$resource', '$http', function($resource, $http) { var User, anonymousUser, currentUser, isLoggedIn; anonymousUser = { uid: 0, pass: null, name: 'Anonymous' }; currentUser = angular.copy(anonymousUser); isLoggedIn = false; User = $resource('api/user/:verb', {}, { login: { method: 'POST', params: { verb: 'login' }, isArray: false, // (Ab)using the transformResponse callback to update currentUser // and isLoggedIn when necessary. transformResponse: $http.defaults.transformResponse.concat([ function (data, headersGetter) { if (angular.isObject(data) && angular.isObject(data.user)) { currentUser = data.user; isLoggedIn = true; } // TODO: Flipping to anonymous user when a login error occurs. Double check if this logic is sound. else { currentUser = angular.copy(anonymousUser); isLoggedIn = false; } return data; } ]) }, logout: { method: 'POST', params: { verb: 'logout' }, isArray: false, // eg: [true] transformed to { result: true } // (Ab)using the transformResponse callback to update currentUser // and isLoggedIn when necessary. transformResponse: $http.defaults.transformResponse.concat([ function (data, headersGetter) { if (angular.isArray(data) && data.length > 0) { if (data[0] === true) { currentUser = angular.copy(anonymousUser); isLoggedIn = false; } return { result: data[0] }; } else { // TODO: Deal with indeterminate state here. Is the user logged in still or not? // TODO: Return error. return { result: false }; } } ]) } }); // FIXME: Adding extra properties onto our $resource here. These ARE visible in the controller but bindings and $watch don't work on them. User.isLoggedIn = isLoggedIn; User.currentUser = currentUser; // FIXME: Attempting to bring these objects under the purview of Angular but this isn't helping. $rootScope.isLoggedIn = isLoggedIn; $rootScope.currentUser = currentUser; return User; }]); /** * The controller. */ angular.module('myApp.page', []) .controller('NavbarCtrl', ['$scope', 'User', function ($scope, User) { // These work, but are not dynamically updated when User.login() and User.logout() are called. $scope.currentUser = User.currentUser; $scope.isLoggedIn = User.isLoggedIn; // FIXME: $watch is only called once, changes in User.login() and User.logout() do not invoke $watch here. $scope.$watch('currentUser', function (newVal, oldVal) { console.log([newVal, oldVal], 'Watching curentUser'); }, true); }])