简体   繁体   English

如何确保promise.then(func)之前已在另一个控制器中运行?

[英]How to ensure a promise.then(func) has run before in another controller?

I have a Restangular function in controller A that needs to set up a $rootScope variable that is being used in controller B. How can I ensure that the Restangular function is run before controller B is initialized, or is there another way to handle this issue? 我在控制器A中有一个Restangular函数,该函数需要设置一个在控制器B中使用的$rootScope变量。如何确保在初始化控制器B之前运行Restangular函数,或者是否有另一种方式来处理此问题? Thanks. 谢谢。

The usual way to handle dependencies is to use a use a $scope.$watch on the variable you're waiting on and have your other code respond in the callback. 处理依赖关系的通常方法是对正在等待的变量使用$scope.$watch ,并使其他代码在回调中响应。

$scope.$watch(function() {
    return $rootScope.resultFromControllerA
}, function(result) {
    if (result) {

        // Configure Controller B
    }
})

Edit, just to add since you suggested it's a promise, just set the promise on the root scope and have your other controller attach to it: 编辑,只是添加(因为您建议这是一个承诺),只需在根作用域上设置该承诺,然后将其他控制器附加到它:

Controller A 控制器A

$rootScope.controllerASetupPromise = Restangular.get()

Controller B 控制器B

$scope.$watch(function() {
    return $rootScope.controllerASetupPromise
}, function(thePromise) {
    if (thePromise) {

        thePromise.then(function(response) {

            // Configure Controller B
        });
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM