Angular factory returning a promise

后端 未结 4 570
我在风中等你
我在风中等你 2020-12-08 09:40

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

4条回答
  •  一向
    一向 (楼主)
    2020-12-08 10:30

    $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.

    Use:-

        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;
           })
    }]);
    

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

提交回复
热议问题