lundi 27 novembre 2017

How to use asynchronous service in ember.js?

Before my ember.js app start, I need to access a entry api to get all those api endpoints and csrf token.

I'm trying to do it in service so the response can be accessed everywhere:

import Service from '@ember/service';
import $ from 'jquery'
export default Service.extend({
  pageData: null,
  init () {
    this._super(...arguments)
    var self = this
    $.ajax({
      type: 'get',
      url: '/page_data',
      dataType: 'json'
    }).then((response) => {
      self.set('pageData', response)
    })
  }
});

And I'm injecting the service in initializer:

export function initialize (application) {
  application.inject('route', 'api', 'service:page-data');
  application.inject('controller', 'api', 'service:page-data');
  application.inject('component', 'api', 'service:page-data');
}

export default {
  initialize
};

But I can't use the service in my router directly with this.get('api').pageData because it's asynchronous.

I found something on ember.js documetation here:

Operations performed in initializers should be kept as lightweight as possible to minimize delays in loading your application. Although advanced techniques exist for allowing asynchrony in application initializers (i.e. deferReadiness and advanceReadiness), these techniques should generally be avoided. Any asynchronous loading conditions (e.g. user authorization) are almost always better handled in your application route's hooks, which allows for DOM interaction while waiting for conditions to resolve.

But it 's used in initializers, not service.

Any suggests what I can do with my service now?




Aucun commentaire:

Enregistrer un commentaire