Typescript async/await doesnt update AngularJS view

前端 未结 10 526
小鲜肉
小鲜肉 2020-12-01 09:17

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

I\'ve noticed that after I change any property which is bound to view in my async funct

10条回答
  •  暖寄归人
    2020-12-01 09:43

    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.

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

    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;
    });
    

    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 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.

提交回复
热议问题