Inject Router using Injector.resolveAndCreate inside a class

时间:2016-02-03 04:02:26

标签: angular router

Is it possible to inject Router using Injector.resolveAndCreate() ?

import {ExceptionHandler, Injectable, Inject,Injector} from 'angular2/core';
import {Router,ROUTER_PRIMARY_COMPONENT} from 'angular2/router';

@Injectable()
export class MyExceptionHandler implements ExceptionHandler{

    constructor(public router: Router) { }
    call(error, stackTrace = null, reason = null) {
        console.log("ERROR >> " + error);
        console.log("STACKTRACE >> " + stackTrace);
        console.log("REASON >> " + reason);
        let injector: any = Injector.resolveAndCreate([Router]);
        let router: Router = injector.get(Router);
        router.navigateByUrl('/error');       
        
    }
}

Getting EXCEPTION: Error during instantiation of Token RouterPrimaryComponent! (e -> Router -> RouteRegistry -> Token RouterPrimaryComponent).

1 个答案:

答案 0 :(得分:1)

Sure, if you use an injector that has ROUTER_PROVIDERS registered, but you usually don't want a Router instance but the Router instance - the one used in the application. For this you need to use the same Injector as the Angular application uses.

This might be what you are looking for Redirect to a different component inside @CanActivate in Angular2