【问题标题】:Execute code within a factory when needed, not when loaded into controller在需要时在工厂内执行代码,而不是在加载到控制器时执行代码
【发布时间】:2015-12-14 19:46:57
【问题描述】:

工厂:

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

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

【问题讨论】:

    标签: angularjs angular-promise angular-services angular-http angular-controller


    【解决方案1】:

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

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

    您还在服务中创建了一个额外的承诺,这首先不需要,因为您可以利用$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
            });
        } 
    }]);
    

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2011-04-14
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 2011-09-21
      相关资源
      最近更新 更多