【问题标题】:Angular-ui-router: Making asynchronous call across state transitionAngular-ui-router:跨状态转换进行异步调用
【发布时间】:2016-12-30 23:32:54
【问题描述】:

我正在尝试将由 onEnter 触发的异步 API 调用设置为新的 .state

onEnter: function(StatFactory){ 
                StatFactory.getStats(function(res){
                    console.log("callback");
            });
    }

到目前为止我注意到的是它首先调用异步函数,然后实例化新状态的控制器,最后触发回调。

该函数会更新工厂内部的数据,但不会更新$scope。

我想也许我需要在新的 $scope 上强制 $apply,但我不知道如何。

有什么想法吗? (我是新手)

【问题讨论】:

    标签: javascript angularjs asynchronous angular-ui-router mean-stack


    【解决方案1】:

    据我所知,onEnter 没有为您提供$scope 来将结果绑定到。

    您可以在创建控制器时调用该函数(IE 控制器的定义块)或使用resolve 状态参数(注意:如果异步函数失败,这将导致状态不被激活)。

    这是resolve 的示例:

    $stateProvider.state('home', {
     ...
     //Will wait for the getStats call to end. You can inject the stats to the controller now.
     resolve: {
      stats: function(StatFactory) { return  StatFactory.getStats(); }
     },
     controller: function($scope, stats){
      //Use stats
      $scope.stats = stats;
     }
    });
    

    【讨论】:

    • 感谢 Muli,这两种解决方案都很棒。在我深入了解 Promise 和双向数据绑定之后,我可以说我的问题听起来有点傻。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多