Replacing $http with Fetch API

前端 未结 2 2006
梦如初夏
梦如初夏 2021-01-19 02:45

I\'m replacing $http with Fetch API and got replaced $q with Promise API. Because of that, Angular didn\'t run digest cycles anymore, thus UI didn\

2条回答
  •  臣服心动
    2021-01-19 03:18

    Convert the ES6 promises created by the fetch API to AngularJS $q promises with $q.when.

    Use $q.when to convert ES6 promises to AngularJS promises1

    AngularJS modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and AngularJS execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc...2 Since the promise comes from outside the AngularJS framework, the framework is unaware of changes to the model and does not update the DOM.

    Use $q.when to convert the external promise to an Angular framework promise:

    var myRequest = new Request('flowers.jpg');
    
    $q.when(fetch(myRequest)).then(function(response) {
        //code here
    })
    

    Use $q Service promises that are properly integrated with the AngularJS framework and its digest cycle.

    $q.when

    Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

    -- AngularJS $q Service API Reference - $q.when

提交回复
热议问题