1
votes

Inject service into a utility Ember-cli ??

I have an Ember utility which makes an ajax call using Ember.$.ajax. But when I get an unauthorised response from the server I want to invalidate the session. For that, I need to access Session service which I am unable to access in utility.

In the following link, it tells how to use util inside service not service inside util https://guides.emberjs.com/v2.12.0/tutorial/service/

1
Refer this answer stackoverflow.com/a/34971940/5771666 it has excellent explanation. try it out and post your attempt with error. - Ember Freak

1 Answers

1
votes
  1. Add Ember application to window scope using initializer:

    a) Generate initializer using Ember CLI:

    ember generate initializer global-app
    

    b) In generated initializer:

    
    export function initialize(application) {
      window.AppContainer = application;
    }
    
    export default {
      name: 'global-app',
      initialize
    };
    
    
  2. Then you can find your service in AppContainer from utils methods:


     const session = window.AppContainer.lookup('service:session');
     session.invalidate();