Search code examples
javascriptangularjsecmascript-6angularjs-scope

How can I insert the $q provider inside a class that is not wrapped into an angular module?


I have an es6 module

MyModule

let _q$;// I would like the $q provider of angularjs to be a private property of that module

export default class MyClass{
   constructor($q){
      _$q = $q
    }
}

Actually, the only way (I found) to instanciate MyClass is from an angularjs function:

import MyClass from "../model/MyClass";
angular.module('myModule').run(function($q){
   var myObject = new MyClass($q);
})

Probleme with it is that I can't access myObject outside current file.

What I would like to do is to instanciate MyClass inside the MyModule, then export it:

class MyClass{
   constructor($q){
      _$q = $q
    }
}

export myObject = new MyClass($q);

probleme here is that I don't know how to access the $q.

I'm a bit stuck :(


Solution

  • The full answer is:

    import angular from 'angular';
    const $injector = angular.injector(['ng']);//<- ['ng'] is necessary to tell angular in which module the provider resides.
    const $q = $injector.get('$q');
    
    class MyClass {
      someMethod() {
        return $q.resolve('something');
      }
    };
    
    export let myObject = new MyClass();