2

Is there a way to reference a service that's provided at bootstrap in static class methods?

Don't have any code at the moment, but I've been trying standard/boilerplate syntax with Injector like here. When I resolveAndCreate() a service (tried other Injector methods too...) new instance is created and bootstraped instance is overwritten.

Intended usecase is with @CanActivate() decorator. I've been doing awful workaround (-: setting window["__ready__"] when service is ready and using that in decorator...

Sasxa
  • 40,334
  • 16
  • 88
  • 102

1 Answers1

5

One solution is to store a reference to the injector created at bootstrap in a dedicated singleton.

bootstrap(App, [Auth, ROUTER_PROVIDERS])
.then((appRef: ComponentRef) => {
  // store a reference to the injector
  appInjector(appRef.injector);
});

The singleton is the following :

let appInjectorRef: Injector;
export const appInjector = (injector?: Injector):Injector => {
    if (injector) {
      appInjectorRef = injector;
    }

    return appInjectorRef;
};

And then you can access the service like that :

let injector: Injector = appInjector(); // get the stored reference to the injector
let auth: Auth = injector.get(Auth); //get the service from the injector

Here is a Plunker where you can see this in action. (I am not the author of the plunker, but this was really helpful to me) : http://plnkr.co/edit/SF8gsYN1SvmUbkosHjqQ?p=preview