Skip to content

FetchQL in angularjs

Cheng Gu edited this page Aug 3, 2017 · 3 revisions

While using FetchQL in angularjs(1.x), you may have a problem:

var ql = new FetchQL();
ql.query()
    .then((response) => {
        /**
         * FetchQL's queries don't lived in angular's lifecycle,
         * so angular's view may not update correctly after you assigned response data to $scope;
         */
        $scope.data = response.data.someQuery;

        /**
         * To solve this problem, you may use $timeout
         */
        $timeout(() => {
            $scope.data = response.data.someQuery;
        });
    });

But it looks like a bit of a hassle.

A recommend way to solve this problem

// angular-fetchql.js
import FetchQL from 'fetchql';

class AngularFetchQL extends FetchQL {
  constructor($q, ...options) {
    super(...options);
    this.$q = $q;
  }

  query(...options) {
    const defer = this.$q.defer();
    const query = super.query(...options);
    query.then(defer.resolve).catch(defer.reject);
    return defer.promise;
  }
}

export default ($q) => {
  return (...options) => {
    return new AngularFetchQL($q, ...options);
  };
};

// services.js
import AngularFetchQL from './angular-fetchql';
angular.module('app.services', [])
  .service('AngularFetchQL', AngularFetchQL);

// app.js
var ql = new AngularFetchQL();
ql.query()
    .then((response) => {
        /**
         * In this way, all queries' promises will be deferred by $q,
         * when you assign response data to $scope,
         * $scope will observe this changes and update view correctly.
         */
        $scope.data = response.data.someQuery;
    });
Clone this wiki locally