需要时在工厂内执行代码,而不是加载到控制器中时

Execute code within a factory when needed, not when loaded into controller

工厂:

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

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

您的工厂有 $http.get 直接在 return 自定义 $q promise 的工厂函数内。因此,当您在控制器函数中注入工厂依赖项时,它会要求 angular 创建一个 myFac 工厂函数的对象,而在创建函数对象时,它会执行您拥有的代码块 return编辑你的工厂,基本上是 return 的承诺。

你可以做的是,只是return一个来自工厂函数的对象{},它将有方法名称及其定义,所以当你在angular控制器中注入时,它会return 服务对象,它将有多种方法,如 getData 方法。每当你想调用工厂的方法时,你可以像 myFac.getData().

那样 factoryName.methodName()

此外,您还在服务中创建了一个最初不需要的额外承诺,因为您可以利用 $http.get 的承诺(return 是一个承诺对象。)

工厂

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