javascript - 处理服务和 Controller 之间的 AngularJS Promise 的推荐方法

标签 javascript angularjs

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

我希望我的工厂首先对配置文件信息发出 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/

相关文章:

javascript - 如何在 Grunt 中将项目变量 config.get() 到任务的 initConfig 中?

javascript - Materialise CSS Collapsible 不展开

javascript - 异步请求中的angularjs简单.then或$q服务

javascript - 如何在 angularJs 中将参数传递给工厂?

javascript - AngularJs ng-消息无法正常工作

javascript - 将选中的属性添加到 TR 中最接近的复选框

javascript - 如何保存 JavaScript Web 应用程序的状态?

javascript - 使用该元素的 html 内容更改 li 元素的背景

javascript - 背景图片的高度和宽度适应每个屏幕尺寸

angularjs - 类型上不存在属性。 typescript