AngularJS - 结合/看它返回一个承诺的函数 [英] AngularJS - binding/watching a function which returns a promise

查看:187
本文介绍了AngularJS - 结合/看它返回一个承诺的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我张贴在AngularJS GitHub的一个问题,但它似乎没有要得到一个一大堆的关注,我是不能够自己修复,因为它是一个pretty低层次的问题,所以我觉得它的时间来寻找一个解决办法。

I posted an issue on the AngularJS github but it doesn't seem to be getting a whole lot of attention and I wasn't able to fix it myself since it's a pretty low-level issue, so I think it's time to look for a workaround.

角让你把一个承诺(或任何以。然后(...)功能)到你的范围,一旦解决了,所有的手表$并绑定到任何承诺将使用解析值。当您使用一个函数返回一个承诺,因为同样的不适产生的问题是 - 它就像一个普通的对象处理

Angular allows you to put a promise (or anything with a .then(...) function) into your scope, and once it is resolved, all $watches and anything bound to that promise will use the resolved value. The issue arises when you use a function to return a promise, as the same doesn't apply - it's handled like a plain object.

例如:

var helloDef = $.Deferred();
$scope.hello = helloDef.promise();

$scope.getHello = function() {
    return $scope.hello;
};

$timeout(function() {
    helloDef.resolve('Hello!');
}, 1000);

小提琴

下面使用 NG-绑定=你好工作正常,输出的您好!的,但 NG-绑定= getHello()输出的 [对象的对象] 的作为内部$手表返回承诺对象。工程与$ Q代替$ .Deferred以同样的方式。

Here using ng-bind="hello" works fine and outputs Hello!, but ng-bind="getHello()" outputs [object Object] as the internal $watch returns the promise object. Works the same way with $q instead of $.Deferred.

在我的实际code我创建的承诺第一次函数被调用,所以我不能只是pre-做出承诺,指的是在范围内。

In my actual code I'm creating the promise the first time the function is called, so I can't just pre-make the promise and refer to that in scope.

我还需要它不仅仅是NG-绑定多,所以使得它正确处理这种情况下是不可行我自己的约束力的指令。

I also need it for more than just ng-bind, so making my own binding directive which handles this case properly isn't viable.

任何人有什么想法?我目前正在返回如果数据没有解决的承诺和实际结果,如果有,但这是一起工作有疼痛感。绑定到数据简要任何导致作为数据被装入,像ngRepeat使用许对象,而不是解析值来创建元素奇怪的副作用

Anyone have any ideas? I'm currently returning the promise if the data hasn't resolved and the actual result if it has, but that's a pain to work with. Anything bound to the data briefly causes weird side effects as the data is being loaded, like ngRepeat using the promise object instead of the resolved value to create elements.

感谢。

更新:拉要求: https://开头github上。 COM /角/ angular.js /拉/ 3605

更新2:供将来参考,自动去包裹的承诺已经去$ P $在1.2 BRACH pcated

UPDATE 2: For future reference, automatic promise unwrapping has been deprecated in the 1.2 brach.

推荐答案

拉请求合并时,它应固定在1.2.0所以我将这个标记作为答案。

Pull request merged, it should be fixed in 1.2.0 so I'll mark this as the answer.

这篇关于AngularJS - 结合/看它返回一个承诺的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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