1

工厂:

.factory("myFac", ['$http', '$q', function($http, $q) {  
    var defer = $q.defer();

    $http.get('some/sample/url').then(function (response) { //success
        /* 
         * Do something with response that needs to be complete before
         * controller code is executed.
         */
        defer.resolve('done');
    }, function() { //error
        defer.reject();
    });

    return defer.promise;
}]);

控制器:

.controller("testCtrl", ['$scope', 'myFac', function($scope, myFac) {
    /*
    * Factory code above is executed immediately as 'myFac' is loaded into controller.
    * I do not want this.
    */

    if($scope.someArbitraryBool === true) {
        //THIS is when I want to execute code within myFac
        myFac.then(function () {
            //Execute code that is dependent on myFac resolving
        });
    } 
}]);

请让我知道是否可以将工厂中的代码延迟到我需要它为止。另外,如果有更好的方法来执行这个概念,请随时纠正。

4

1 回答 1

0

您的工厂$http.get直接在工厂函数内部返回自定义 $q 承诺。因此,当您在控制器函数中注入工厂依赖项时,它会要求 Angular 创建myFac工厂函数对象,而在创建函数对象时,它会执行您返回工厂的代码块,基本上它会返回 Promise。

您可以做的是,只需{}从工厂函数返回一个对象,该对象将具有方法名称及其定义,因此当您在角度控制器中注入时,它将返回服务对象,该对象将包含各种方法,如getData方法。每当你想调用工厂的方法时,你都可以这样factoryName.methodName()myFac.getData()

此外,您在服务中创建了一个额外的承诺,这首先不需要,因为您可以利用的承诺$http.get(它返回一个承诺对象。)

工厂

.factory("myFac", ['$http', function($http) {
    var getData = return $http.get('some/sample/url').then(function (response) { //success
        return 'done'; //return to resolve promise with data.
    }, function(error) { //error
        return 'error'; //return to reject promise with data.
    });

    return {
        getData: getData
    };

}]);

控制器

.controller("testCtrl", ['$scope', 'myFac', function($scope, myFac) {    
    if($scope.someArbitraryBool === true) {
        //Here you could call the get data method.
        myFac.getData().then(function () {
            //Execute code that is dependent on myFac resolving
        });
    } 
}]);
于 2015-12-14T19:49:09.647 回答