4

I know I can inject store inside a component constructor like this :

constructor(private store:Store){

   store.select('thing').subscribe(
    ()=>{ 
          console.log('do my thing'); // Got the thing
         }
   );
}

But I want to create a decorator to be able to use this select inside it , so I want to inject Store inside my decorator :

export function Select<T> ( selector ) {
    return function decorate ( target : any , key : string ) : void {
        let injector = ReflectiveInjector.resolveAndCreate( [
            StoreModule.provideStore(()=>{} , {}).providers
        ] );
        let store    = injector.get( Store );
        store.select( 'thing' ).subscribe( ()=> {
            console.log( 'do my thing',thing ); // thing is undefined
        } );
    }
}

Weird thing is Store is not an Injectable class( looking at the source code ) and it needs 3 property to be passed to be able to instantiate it ( Reducers , State and one more ).

So how does Angular itself can inject that class in constructor, without providing those arguments , but when I'm trying to inject , it needs them?

I've literally tried all the different Injector and ReflectiveInjector methods , none of them works for me .

  • Store isn't a singleton, right? This creates a new injector instance, and store instance doesn't appear anywhere but in decorator function scope. – Estus Flask Sep 10 '16 at 16:37
  • @estus , that's exactly my question , it it's not singleton , and if it needs some parameters , then how come when you inject it with constructor of the component , it gives you the the root store , as a singleton –  Sep 11 '16 at 00:06
  • Yes , if you don't know the answer , down vote makes you feel better. –  Sep 11 '16 at 00:07
  • ReflectiveInjector creates a new injector instance that is unrelated with current app (the same pitfall is `angular.injector` for A1 if you had a chance), so it isn't helpful here. AFAIK there's no way to get an access to component's injector from decorator if `Injector` wasn't injected into a component. – Estus Flask Sep 11 '16 at 00:23
  • There is a hacky technique for making root injector available from the outside (decorator function scope is considered 'outside'), and it seems that [there are problems with it in latest A2 versions](https://stackoverflow.com/questions/39409328/storing-injector-instance-for-use-in-components) – Estus Flask Sep 11 '16 at 00:24

0 Answers0