我已经编写了一个后端服务,该服务由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请求配置文件信息。这是好的做法,还是在工厂中缓存信息是更好的主意?
编辑:更新的代码(基于来自@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()?
您可以将服务创建为跨控制器之类的存储
angular.module('app.social', ['ngResource'])
.service("SocialService", function() {
var info = {
me: null,
friends: []
};
return info;
})
.factory('Social', function($http, SocialService) {
return {
me: function() {
$http.get('http://localhost:3000/me').then(function(response){
SocialService.me = response.data;
});
},
然后在所有控制器中,引用infoService
而不是再次调用API。您需要获取最新数据并刷新infoService
,所有控制器作用域都会收到此更改的通知。
在您的控制器中
angular.module('app.profile', [])
.controller('ProfileCtrl', ['$window', '$scope', 'SocialService', 'Social', function($window, $scope, SocialService, Social) {
$scope.SocialService = SocialService;
// Kick off social factory to update user info, you can move it into
// any other functions like `ng-click`.
Social.me();
}])
然后在您看来
{{SocialService.me}}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句