AngularJS - 为什么$所适用需要妥善解决$ Q承诺? [英] AngularJS - why is $apply required to properly resolve a $q promise?

查看:101
本文介绍了AngularJS - 为什么$所适用需要妥善解决$ Q承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着写在我的角度应用程序的小服务,这将使我去接全球JavaScript对象指定的配置参数。我不想尝试访问全局配置对象,除非该文件已准备好(因为我不能保证在脚本元素将在HTML中插入的顺序)。

不过,我不明白为什么我需要调用 $适用的决议,实际上传播到然后回调。

  myModule.service('GlobalConfigService',['$ Q','$ rootScope',函数($ Q $ rootScope){
    变种高清= $ q.defer();
    $(文件)。就绪(函数(){
        def.resolve(MyConfig.val);
        $ rootScope $适用()。
    });    def.promise.then(函数(){
        的console.log(我叫只有当$适用()被调用,为什么呢?');
    });    返回def.promise;
}]);


解决方案

在AngularJS决心的结果()异步传播,一个$消化周期内,不会立即进行。这意味着,与随后()注册的回调才会被调用(后)时的摘要周期发生

在您的code,没有什么是造​​成角进入消化循环,所以当时()回调不会被调用。调用$应用()是引起消化周期来运行的一种方法。另一种方法:添加具有NG-点击一个按钮,什么也不做,然后单击,就会造成消化周期,你应该看到的结果:

 <按钮NG点击=>强制通过点击我&LT消化; /按钮>

另请参阅 http://stackoverflow.com/a/14657974/215945

I'm trying to write a small service in my angular app which will enable me to pick config parameters specified in global Javascript objects. I don't want to attempt accessing the global config object unless the document is ready (because I cannot guarantee the order in which script elements will be inserted in the HTML).

However, I can't understand why I need the call to $apply for the resolution to actually propagate to the then callback.

myModule.service('GlobalConfigService', ['$q', '$rootScope', function($q, $rootScope) {
    var def = $q.defer();
    $(document).ready(function() {
        def.resolve(MyConfig.val);
        $rootScope.$apply();
    });

    def.promise.then(function () {
        console.log('I am called only when $apply() is called. Why?');
    });

    return def.promise;
}]);

解决方案

In AngularJS the results of resolve() are propagated asynchronously, inside a $digest cycle, not immediately. This means that callbacks registered with then() will only be called (later) when a digest cycle occurs.

In your code, nothing is causing Angular to enter a digest cycle, so the then() callback is never called. Calling $apply() is one way to cause a digest cycle to run. Another way: add a button with ng-click that does nothing, then click that, it will cause a digest cycle and you should see the results:

<button ng-click="">Force digest by clicking me</button>

See also http://stackoverflow.com/a/14657974/215945

这篇关于AngularJS - 为什么$所适用需要妥善解决$ Q承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆