打字稿异步/等待不会更新AngularJS视图 [英] Typescript async/await doesnt update AngularJS view

查看:102
本文介绍了打字稿异步/等待不会更新AngularJS视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Typescript 2.1(开发人员版本)将异步/等待转换为ES5.

I'm using Typescript 2.1(developer version) to transpile async/await to ES5.

我注意到,在我更改了必须在异步函数中查看的任何属性之后,该视图不会使用当前值进行更新,因此每次我都必须在$结尾处调用$ scope.$ apply().功能.

I've noticed that after I change any property which is bound to view in my async function the view isn't updated with current value, so each time I have to call $scope.$apply() at the end of function.

异步代码示例:

async testAsync() {
     await this.$timeout(2000);
     this.text = "Changed";
     //$scope.$apply(); <-- would like to omit this
}

此后,视图中不会显示新的text值.

And new text value isn't shown in view after this.

有没有解决方法,所以我不必每次都手动调用$ scope.$ apply()?

Is there any workaround so I don't have to manually call $scope.$apply() every time?

推荐答案

此处的答案是正确的,因为AngularJS不了解该方法,因此您需要告诉" Angular有关已更新的任何值.

The answers here are correct in that AngularJS does not know about the method so you need to 'tell' Angular about any values that have been updated.

我个人将$q用于异步行为,而不是将await用作其角度方式".

Personally I'd use $q for asynchronous behaviour instead of using await as its "The Angular way".

您可以很容易地用$ q包裹非Angular方法,即[注意,这是我包裹所有Google Maps函数的方式,因为它们都遵循这种传递回调的模式,以通知完成情况.

You can wrap non Angular methods with $q quite easily i.e. [Note this is how I wrap all Google Maps functions as they all follow this pattern of passing in a callback to be notified of completion]

function doAThing()
{
    var defer = $q.defer();
    // Note that this method takes a `parameter` and a callback function
    someMethod(parameter, (someValue) => {
        $q.resolve(someValue)
    });

    return defer.promise;
}

然后您可以像这样使用它

You can then use it like so

this.doAThing().then(someValue => {
    this.memberValue = someValue;
});

但是,如果您希望继续使用await,则在这种情况下,有一种比使用$apply更好的方法,并且可以使用$digest.像这样

However if you do wish to continue with await there is a better way than using $apply, in this case, and that it to use $digest. Like so

async testAsync() {
   await this.$timeout(2000);
   this.text = "Changed";
   $scope.$digest(); <-- This is now much faster :)
}

在这种情况下,

$scope.$digest更好,因为$scope.$apply将对所有作用域上的所有绑定值执行脏检查(用于更改检测的Angulars方法),这在性能上可能是昂贵的-特别是如果您有许多绑定.但是,$scope.$digest将仅对当前$scope中的边界值执行检查,从而使其性能更高.

$scope.$digest is better in this case because $scope.$apply will perform dirty checking (Angulars method for change detection) for all bound values on all scopes, this can be expensive performance wise - especially if you have many bindings. $scope.$digest will, however, only perform checking on bound values within the current $scope making it much more performant.

这篇关于打字稿异步/等待不会更新AngularJS视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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