角工厂返回一个承诺 [英] Angular factory returning a promise

查看:118
本文介绍了角工厂返回一个承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序开始我从服务器加载一些设置。我的大多数控制器需要这个东西之前可以做到非常有用。我想尽可能简化控制器的code。我的尝试,这是不行的,是这样的:

When my app starts I load some settings from a server. Most of my controllers need this before anything useful can be done. I want to simplify the controller's code as much as possible. My attempt, which doesn't work, is something like this:

app.factory('settings', ['$rootScope', '$http', '$q', function($rootScope, $http, $q) {
    var deferred = $q.defer();

    $http.get('/api/public/settings/get').success(function(data) {
        $rootScope.settings = data;
        deferred.resolve();
    });

    return deferred.promise;
}]);

app.controller('SomeCtrl', ['$rootScope', 'settings', function($rootScope, settings) {
    // Here I want settings to be available
}]);

我想避免有很多settings.then的(功能()...)随处可见。

I would like to avoid having a lot of settings.then(function() ...) everywhere.

如何解决这一个很好的方式,任何想法?

Any ideas on how to solve this in a nice way?

推荐答案

$ HTTP自动返回答应你不需要绑定在$ Q这里面是不是一个好的做法,并认为是反模式。

$http itself return promise you don't need to bind it inside the $q this is not a good practice and considered as Anti Pattern.

使用: -

    app.factory('settings', ['$rootScope', '$http', '$q', function($rootScope, $http) {
        return $http.get('/api/public/settings/get')
    }]);

    app.controller('SomeCtrl', ['settings',$scope, function(settings,$scope) {
        settings.then(function(result){
                $scope.settings=result.data;
          });
    }]);

您的方式可以做到: -

Your way can be done as :-

app.factory('settings', ['$rootScope', '$http', '$q', function($rootScope, $http, $q) {
    var deferred = $q.defer();

    $http.get('/api/public/settings/get').success(function(data) {
        deferred.resolve(data);
    });

    return deferred.promise;
}]);

app.controller('SomeCtrl', ['$scope', 'settings', function($scope, settings) {
    settings.then(function(data){
          $scope.settings=data;
       })
}]);

不要超载$ rootScope,如果你想它,你需要使用$监视在$ rootScope的变化(不推荐)。

Don't overload $rootScope if you wanted it you need to use $watch for the changes in $rootScope(Not recommended).

这篇关于角工厂返回一个承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆