我编写了一个后端服务,供 Angular.JS 前端使用工厂使用,如下所示:
angular.module('app.social', ['ngResource'])
.factory('Social', function($http) {
return {
me: function() {
return $http.get('http://localhost:3000/me');
},
likeVideo: function(link) {
return $http.post('http://localhost:3000/like/video', { link : link });
},
post: function(link) {
return $http.post('http://localhost:3000/post', { link : link });
},
postVideo: function(link) {
return $http.post('http://localhost:3000/post/video', { link : link });
},
friends: function() {
return $http.get('http://localhost:3000/friends');
},
taggableFriends: function() {
return $http.get('http://localhost:3000/friends/taggable');
},
videos: function() {
return $http.get('http://localhost:3000/videos');
}
};
});
Social.me 端点从 REST 后端接收配置文件信息。然而,此功能用于各种 Angular 控制器(个人资料页面、项目详细信息页面、标题帐户按钮等)。这意味着对于每个视图,都会请求个人资料信息http://localhost:3000/me http://localhost:3000/me。这是一个好的做法,还是在工厂内缓存信息是一个更好的主意?
编辑:更新的代码(基于@Rebornix的答案):
angular.module('app.social', ['ngResource'])
.service('SocialService', function() {
var serviceData = {
me: null
};
return serviceData;
})
.factory('Social', function($http, SocialService) {
return {
me: function() {
if (SocialService.me === null) {
return $http.get('http://localhost:3000/me').then(function(response) {
SocialService.me = response.data;
return SocialService.me;
});
} else {
return SocialService.me;
}
}
}
};
});
在控制器中,我使用:
angular.module('app.profile', [])
.controller('ProfileCtrl', ['$window', '$scope', 'Social', function($window, $scope, Social) {
$scope.me = Social.me();
}])
和观点:
<div ng-controller="ProfileCtrl">
<h1 class="profile-name">{{ me.name }}</h1>
</div>
但视图不会更新,因为 Facebook.me 值在第一个请求时被初始化。我想我必须以某种方式手动触发 $scope.$apply() ?