AngularJS - 绑定/监视返回承诺的函数 [英] AngularJS - binding/watching a function which returns a promise

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

问题描述

我在 AngularJS github 上发布了一个问题,但似乎没有得到了很多关注,但我无法自己修复它,因为这是一个非常低级的问题,所以我认为是时候寻找解决方法了.

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 允许你将承诺(或任何带有 .then(...) 函数的东西)放入你的范围,一旦它被解析,所有 $watches 和任何绑定到该承诺的东西将使用解析值.当您使用函数返回承诺时会出现问题,因为这并不适用 - 它像普通对象一样处理.

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-bind="hello" 工作正常并输出 Hello!,但 ng-bind="getHello()"输出 [object Object] 作为内部 $watch 返回承诺对象.使用 $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.

在我的实际代码中,我是在第一次调用函数时创建承诺,所以我不能只是预先做出承诺并在范围内引用它.

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-bind,还需要它,所以制作我自己的绑定指令来正确处理这种情况是不可行的.

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 使用 promise 对象而不是解析值来创建元素.

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/angular.js/pull/3605

更新 2:为了将来参考,自动承诺解包已在 1.2 分支中弃用.

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天全站免登陆