Typescript async/await 不更新 AngularJS 视图 [英] Typescript async/await doesnt update AngularJS view

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

问题描述

我正在使用 Typescript 2.1(开发者版本)将 async/await 转换为 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 作为它的Angular 方式".

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.

这篇关于Typescript async/await 不更新 AngularJS 视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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