下面显示的代码适用于我的目的,但我想确认这是否被视为最佳实践。
我希望我的工厂首先对配置文件信息发出 http 请求,然后在后续请求中简单地重用此数据。
ProfileService.js
app.factory('ProfileService', ['$http', '$q', function($http, $q) {
var profile;
return {
getProfile: function() {
if (profile === undefined) {
return $http.get('url/to/profile.json').then(function(response) {
profile = response;
return profile;
});
}
return $q.when(profile);
}
};
}]);
我有两个 Controller ,它们利用 ProfileFactory 来访问此数据的元素。
HomeController.js
app.controller('HomeController', ['ProfileService', function(ProfileService) {
var self = this;
ProfileService.getProfile().then(function(result) {
self.name = result.name;
self.showAlert = result.showAlert;
});
}]);
ProfileController.js
app.controller('ProfileController', ['ProfileService', function(ProfileService) {
var self = this;
ProfileService.getProfile().then(function(result) {
self.profile = result;
self.profile.showAlert = false;
});
}]);
任何有关此方法的反馈将不胜感激。
最佳答案
我认为这是最好的方法。在我看来,让服务返回一个 promise 供 Controller 使用是最好的关注点分离。
关于javascript - 处理服务和 Controller 之间的 AngularJS Promise 的推荐方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34345137/