Lazy fetch in background after rendering the page


#1

I have a simple page “authors” that shows a list of authors.

Each author of course has many books, but in that page (and in the API) I don’t show(/include) any book data.

In the authors route I have the default model():

model() {
  return this.store.findAll('author');
}

and everything is OK.

Now I need something that fetch lazy (in background) some data from others APIs (the books ones).

But I don’t want this call blocking my authors page render. So, I have the default and speedy beforeModel(), model() and afterModel() without any fetch (except for authors data).

ONLY after page is rendered I need something (maybe a service?) that calls “api/books?author:1,2,3,4,5...

In this way I already have the books in my “store” when someone click on an athor (no waiting loader in that book page).

How to do this?


#2

In the setupController function of your route, you could do something like this. You might need to wrap it in a Ember.run.later() call if the render hasn’t been called yet.

Ember.run.scheduleOnce('afterRender', this, function() {
    // Load your stuff
})

#3

You can still use the afterModel hook for this. As long as you don’t return whatever it is your trying to do then transition will continue unabated. Its only if you return the promise in the afterModel hook that it will wait. You can read about this in the return part of the ember docs for afterModel. For example :

afterModel() {
  // I will wait
  return somePromise.then().catch();
}


afterModel() {
  // I will NOT wait
  somePromise.then().catch();
}