Replacing $http with Fetch API

给你一囗甜甜゛ 提交于 2019-12-01 20:16:21

问题


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't render. To solve this problem I tried Zone.js and that seems to solve our problems partially. Unfortunately its API completely changed in 0.6 so we're using legacy 0.5.15.

Now to the actual problem.

When refreshing the page Angular configs and bootstraps the application like expected. In this phase I'm initializing the Zone and decorating the $rootScope.apply with the Zone and $rootScope.$digest(). Now when I transition between states/routes (with ui-router) everything works as expected, but when full refreshing there's a race condition and the zone/digest doesn't run correctly. I'm not sure how to fix it.

I have the following code in a angular.run() block:

console.log('Zone setup begin');
const scopePrototype = $rootScope.constructor.prototype;
const originalApply = scopePrototype.$apply;
const zoneOptions = {
    afterTask: function afterTask() {
        try {
            $rootScope.$digest();
        } catch (e) {
            $exceptionHandler(e);
            throw e;
        }
    }
};

scopePrototype.$apply = function $applyFn() : void {
    const scope = this;
    const applyArgs = arguments;

    window.zone.fork(zoneOptions).run(() => {
        originalApply.apply(scope, applyArgs);
        console.log('Zone + $digest run!');
    });
};
console.log('Zone setup end');

Above you can see that I log to the console when the Zone initialization begins, when it ends and when it's run (+ Angular digest cycle). In my controller where I fetch the data via Fetch API I've added a console.log('Data fetched!'); so I know when the data has been fetched.

Now the output in console:

State transition with ui-router (works perfectly)

Notice that the digest is run in the end.

Zone setup begin
Zone setup end
Zone + $digest run!
Zone + $digest run!
Zone + $digest run!
Zone + $digest run!
Data fetched!
Zone + $digest run!

Full refresh on state/route (doesn't run in the end)

Zone setup begin
Zone setup end
Zone + $digest run!
Zone + $digest run!
Zone + $digest run!
Zone + $digest run!
Data fetched!

As you can see the Zone/digest doesn't run after the data is fetched, which is why the data and UI isn't rendered on the page.


回答1:


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




回答2:


Rationale

Wrapping $q.when will work but in my team's experience it will be very finicky and prone to error. As one example, returning $q.when from inside the body of a Promise.then function will still chain as a regular Promise and you won't get a $digest on callbacks.

It also requires all authors to understand the difference between two very similar looking constructs (Promise/$q) and care about their concrete types for every level of an asynchronous call. If you are using modern conveniences like async/await (which abstracts the Promise types further), you're gonna be in even more trouble. Suddenly none of your code can be framework agnostic.

Our team decided it was worth committing a big monkey patch to ensure all the promises (and the async/await keywords) "just worked" without needing additional thinking.

Ugly? Yes. But we felt it was an okay tradeoff.


Patch Promise callbacks to always apply $rootScope

First we install the patch against Promise in a angular.run block:

angular.module(...).run(normalizePromiseSideEffects);

normalizePromiseSideEffects.$inject = ['$rootScope'];

function normalizePromiseSideEffects($rootScope) {
  attachScopeApplicationToPromiseMethod('then');
  attachScopeApplicationToPromiseMethod('catch');
  attachScopeApplicationToPromiseMethod('finally');

  function attachScopeApplicationToPromiseMethod(methodName) {
    const NativePromiseAPI = window.Promise;
    const nativeImplementation = NativePromiseAPI.prototype[methodName];

    NativePromiseAPI.prototype[methodName] = function(...promiseArgs) {
      const newPromiseArgs = promiseArgs.map(wrapFunctionInScopeApplication);
      return nativeImplementation.bind(this)(...newPromiseArgs);
    };
  }

  function wrapFunctionInScopeApplication(fn) {
    if (!isFunction(fn) || fn.isScopeApplicationWrapped) {
      return fn;
    }

    const wrappedFn = (...args) => {
      const result = fn(...args);
      // this API is used since it's $q was using in AngularJS src
      $rootScope.$evalAsync();
      return result;
    };
    wrappedFn.isScopeApplicationWrapped = true;
    return wrappedFn;
  }
}

Async/Await

If you want to support the use of async/await, you'll also need to configure Babel to always implement the syntax as Promises. We used babel-plugin-transform-async-to-promises.



来源:https://stackoverflow.com/questions/45827733/replacing-http-with-fetch-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!