处理服务和控制器之间AngularJS Promises的推荐方法

Recommended way to handle AngularJS Promises between Service and Controllers

本文关键字:方法 Promises AngularJS 服务 控制器 之间 处理      更新时间:2023-09-26

下面显示的代码适用于我的目的,但我想确认这是否被视为最佳实践。

我希望我的工厂在第一个实例中对配置文件信息发出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);
        }
    };
}]);

我有两个控制器,然后利用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;
    });
}]);

我们将非常感谢对这种方法的任何反馈。

我认为这是最好的方法。让服务返回控制器使用的承诺是imo的最佳关注点分离。

是的,最好在服务中使用http调用。传统上,我们持有承诺而不是数据,比如:

app.factory('ProfileService', ['$http', function($http) {
    var profilePromise;
    return {
        getProfile: function() {
            if (profilePromise === undefined) {
                profilePromise = $http.get('url/to/profile.json');
            }
            return profilePromise;
        }
    };
}]);