我有这个代码主要工作,但我很难看到更改从我的控制器中的用户对象传播。
我想要做的是构建一个User
服务来管理我网站上当前用户的所有方面。例如:User.login()
,User.logout()
,User.currentUser
,User.isLoggedIn
等
请记住,我还是比较新的角度和ngResource :-)。
- 有没有更好/更角度的方式来设计这个?
- $资源工厂的自定义属性甚至可能吗?
感觉我可能需要一个
$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); }])
谢谢@dolgishev我会尝试这种方法。希望通过类似的对象避免许多不同,例如:User,UserResource等,但也许这是唯一的方法。 –
你可以在你的服务中创建变量,这是一个资源,并添加方法来保存,查询等服务 – dolgishev