处理AngularJS中的许多决议

时间:2016-04-05 09:46:56

标签: javascript angularjs model-view-controller dependency-injection

我遇到了一半的控制器依赖关系被解决的问题,并且在注入服务后我最终得到了7-8个参数。

消退:

resolve{

     first_data:function(){},
     second_data: function(){},
     third_data: function(){}


}

控制器:

function homeCtrl(first_data, second_data, third_data, ModalService, $state, $timeout, homeService, dataService){

})

有没有办法将所有结果放入一个参数?

1 个答案:

答案 0 :(得分:0)

$q怎么样?

let promises = [promiseAlpha(), promiseBeta(), promiseGamma()];

$q.all(promises).then(values => {
    console.log(values[0]); // value alpha
    console.log(values[1]); // value beta
    console.log(values[2]); // value gamma

    complete();
});

甚至:

let promises = {
    alpha: promiseAlpha(),
    beta: promiseBeta(),
    gamma: promiseGamma()
}
$q.all(promises).then(values => {
    console.log(values.alpha); // value alpha
    console.log(values.beta); // value beta
    console.log(values.gamma); // value gamma

    complete();
});

致谢:http://www.martin-brennan.com/using-q-all-to-resolve-multiple-promises/

问题是?是first_data http电话吗?如果是,请使用上述解决方案。 如果first_data是包含数据的容器,只需将其移至service,然后在任意位置调用此服务,例如:

<强> service.js

(function () {
    'use strict';

    angular
        .module('app')
        .service('DashboardService', DashboardService);

    DashboardService.$inject = ['$http'];

    function DashboardService($http) {

        var _this = this;

        _this.first_data = function () {
            return [{id: 1, content: "some data"}];
        };

        return _this;
    }

}());

<强> controller.js

(function () {
    'use strict';

    angular
        .module('app')
        .controller('DashboardCtrl', DashboardCtrl);

    DashboardCtrl.$inject = ['$scope', 'DashboardService'];

    function DashboardCtrl($scope, DashboardService) {

        var _this = this;

        _this.first_data = DashboardService.first_data;
    }
}());