【问题标题】:Run the function after other functions in $onInit are done在 $onInit 中的其他函数完成后运行该函数
【发布时间】:2018-01-14 01:23:15
【问题描述】:

在我的 $onInit 函数中,我有两个获取数据的函数。我在需要前两个数据的地方使用第三个函数。我在第三个函数中执行的逻辑是将在屏幕上呈现的内容。如何在 $onInit 中使用回调并确保第三个函数不会在前两个函数之前运行?

 ctrl.$onInit = $onInit;

    function $onInit() {
        getFood();
        getDrinks();

        combineFoodAndDrinks();
    }

编辑我的代码示例

 var ctrl = this;
 ctrl.company = {};
 ctrl.company.administrators = [];
 ctrl.administrators = [];
 ctrl.$onInit = $onInit;
 ....

function $onInit() {
        $q.all([getCompanies(), getAdministrators()]).then(findAdministrators);
        getUnasignedAdministrators();
    }

    function getCompanies() {
        companiesService.getCompanies()
            .then(function (data) {
                var company = data.items.find(function (company) {
                    if ($stateParams.id === company.id) {
                        return company;
                    }
                });
                ctrl.company.name = company.name;
                ctrl.company.contactPerson = {
                    firstName: company.contactPersonName,
                    lastName: company.contactPersonLastName,
                    phone: company.contactPersonPhone
                };
            })
            .catch(function (response) {
                responseService.displayError(response);
            });
    }

    function getAdministrators() {
        administratorsService.getAdmins()
            .then(function (data) {
                ctrl.administrators = data.items;
            })
            .catch(function (response) {
                responseService.displayError(response);
            });
    }

    function findAdministrators() {
        console.log("getCompanies", ctrl.company);
        console.log("getAdministrators", ctrl.administrators);
    }

【问题讨论】:

    标签: angularjs ngoninit


    【解决方案1】:

    您应该考虑从getFoodgetDrinks 方法返回promise,并在完成这两个方法promise 时调用combineFoodAndDrinks。一般来说,sn-p 代码如下所示。

    ctrl.$onInit = $onInit;
    
    function getFood(){
       return $http.get('getFoodurl')
    }
    
    function getDrinks(){
       return $http.get('getDrinksurl')
    }
    
    function combineFoodAndDrinks(data){
       console.log("getFood data", data[0])
       console.log("getDrinks data", data[1])
    }
    
    function $onInit() {
        $q.all([getFood(), getDrinks()]).then(combineFoodAndDrinks);
    }
    

    【讨论】:

    • 感谢 Pankaj。我试过了,但我仍然无法让它工作。我在第一篇文章中添加了我的代码。管理员总是返回空数组,但我会返回公司。
    猜你喜欢
    • 2019-11-25
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 2013-02-03
    • 2019-04-21
    • 1970-01-01
    相关资源
    最近更新 更多