Jorin
Jorin

Reputation: 1336

Using Router Class inside function

I am writing some route helper functions for my angular2 app.. is it possible to inject Router class in normal function.... instead of injecting it in the constructor of class.

I am trying to do something like this

 import {Router} from "angular2/router";
    export function show404()
    {
        var _location=new Location();
        var _router=new Router(.......);
        this._location.replaceState('/');
        this._router.navigateByUrl('/404/');

    }

Is it possible to use Router class like this, If it is possible then how can I?

Upvotes: 1

Views: 66

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657376

Angular DI only injects into constructors and only for instances it creates itself.

What you can do though is to use the injector and request the router from the injector.

bootstrap(AppComponent, [
    ROUTER_PROVIDERS,
]).then((appRef: ComponentRef) => {
  console.log("booting")
    appInjector(appRef.injector);
});

...

let router = appInjector.get(Router);

For a full working example see this Plunker from this discussion https://github.com/angular/angular/issues/4112.

Upvotes: 1

Related Questions