子控制器在angularjs中的父控制器api调用之前加载

问题描述 投票:0回答:1

我使用角度1.6,我有一个父状态和子状态与他们各自的控制器。在我的第一个登录页面中,将有两个链接调用父状态和子状态。当我被称为父州时,它工作正常。但是从登录页面调用子状态,控制台中会出现一些错误,例如“id”未定义。我在父控制器中发出一个Restangular api请求。在这个响应后,我需要加载子控制器?但是当我直接调用子状态时,子控制器在父控制器api调用完成之前加载。怎么解决这个?

看看这个傻瓜。

https://embed.plnkr.co/aUnHIzuFV7GpiDuKyrwZ/

angularjs angular-ui-router restangular angular-ui-router-extras
1个回答
0
投票

在父控制器中保存API调用的promise:

$scope.restPromise = Restangular.one('collections')
.get()
.then(function(data){ 
  $state.go("parentstate.childstate");
  $scope.myData = data;
  $scope.params={
  name:"my_name",
  type:"generic",
  data:data
  };     
});

在子控制器中,使用promise等待API调用:

function ChildCtrl($scope) {
  $scope.restPromise.then(function() {
    console.log($scope.params);
    $scope.params.id=5;
    $scope.title = 'Child State';
  });
}

DEMO on PLNKR

© www.soinside.com 2019 - 2024. All rights reserved.