// Define a factory
app.factory('profilePromise', ['$q', 'AccountService', function($q, AccountService) {
var deferred = $q.defer();
AccountService.getProfile().then(function(res) {
deferred.resolve(res);
}, function(res) {
deferred.resolve(res);
});
return deferred.promise;
}]);
// use a factory
// parent controller user
$scope.getPersonalInfo = function() {
profilePromise.then(function(res) {
var profile = res.content;
........
// define a scope used on child
$scope.profilePromise = profilePromise;
原由:有时候在前端开发的时候,需要多次调用同一个http请求,若多次加载不仅不浪费不必要的http请求,还会多处代码维护,为开发带来诸多不变。
另一方面使用$boardcast父级发送消息数据给子级,子级经常会遇到异步操作无法正确获取需要的数据。
特此添加factory,一处添加维护,其他地方直接使用即可。
参考:http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/
若有疑问,请发表评论或添加微信为你解答:

2661

被折叠的 条评论
为什么被折叠?



