Typescript async/await doesnt update AngularJS view

前端 未结 10 469
小鲜肉
小鲜肉 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:59

    As @basarat said the native ES6 Promise doesn't know about the digest cycle.

    What you could do is let Typescript use $q service promise instead of the native ES6 promise.

    That way you won't need to invoke $scope.$apply()

    angular.module('myApp')
        .run(['$window', '$q', ($window, $q) =>  {
            $window.Promise = $q;
        }]);
    
    0 讨论(0)
  • 2020-12-01 09:59

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

    This is because TypeScript uses the browser native Promise implementation and that is not what Angular 1.x knows about. To do its dirty checking all async functions that it does not control must trigger a digest cycle.

    0 讨论(0)
  • 2020-12-01 10:02

    As it already has been described, angular does not know when the native Promise is finished. All async functions create a new Promise.

    The possible solution can be this:

    window.Promise = $q;

    This way TypeScript/Babel will use angular promises instead. Is it safe? Honestly I'm not sure - still testing this solution.

    0 讨论(0)
  • 2020-12-01 10:07

    In case you're upgrading from AngularJS to Angular using ngUpgrade (see https://angular.io/guide/upgrade#upgrading-with-ngupgrade):

    As Zone.js patches native Promises you can start rewriting all $q based AngularJS promises to native Promises, because Angular triggers a $digest automatically when the microtask queue is empty (e.g. when a Promise is resolved).

    Even if you don't plan to upgrade to Angular, you can still do the same, by including Zone.js in your project and setting up a similar hook like ngUpgrade does.

    0 讨论(0)
提交回复
热议问题