Search code examples
ember.jsember-cli

Shared data between various controllers


I have a project where I need to build an Ember application. The application will have many routes and some of the routes will have some model.

My problem at the moment is that some information is global, meaning they are present in each page (.hbs) and I need to update it periodically.

I've tried to put information on the application route like the following but it didn't work, the content is not accessible on other routes:

import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    return Ember.$.getJSON('/api/users/current')
  }
});

I've also tried to reload the information with a setInterval but this didn't work either.

import Ember from 'ember';

export default Ember.Route.extend({
  init: function() {
    var thyself = this;
    var interval = setInterval(function(){
      thyself.my_reload()
    }, 1000);
    this.set('interval', interval);
    this.set('counter', {});
  },
  my_reload: function() {
    var counter = this.get('counter');
    if (counter >= 10) {
      clearInterval(this.get('interval'));
    }
    this.set('data', Ember.$.getJSON('/api/users/current'));
  }
});

Where can I place this information so it will be available on all routes? And how can I reload the information periodically?

I'm using ember-cli


Solution

  • @NicosKaralis, you should use service for it.

    You can generate it by command: ember generate service name-of-service

    And there you should create methods. When you want to get access from your controller you should inject it in your controller:

    nameOfService: Ember.inject.service(), (remember camelCase here)

    and if you want some method from your service in your controller you will use it like this (example with computed property, you can also use it without computed property):

    someComputedFunctionInController: Ember.computed(function() {
      this.get('nameOfService').yourFunctionFromService();
    },
    
    nextComputedFunctionInController: Ember.computed(function() {
      this.get('nameOfService.getSomethingFromService');
    }
    

    for more: https://guides.emberjs.com/v2.7.0/tutorial/service/

    Hope, it will help you.