问题
In my Angular 2 project I have a custom function goToObject(objectType:string, objectID: number)
that I use to navigate to different objects throughout a couple of different components in my application. The function looks as follows:
goToObject(objectType:string, objectID: number) {
this._router.navigate([type, id]);
}
I was wondering if there is a way to provide this function throughout my complete project, without having to define it in each component separately. What makes it harder I guess is that this function needs to use a instance of a router object. Would I have to try to provide it in my base component?
回答1:
You can use a shared service
@Injectable()
export class RouteServices {
constructor(private _router:Router) {}
navigate(...) {
this._router.navigate([type, id]);
}
}
then provide it at the root component and inject it where you want to use it and call its methods.
来源:https://stackoverflow.com/questions/37773529/how-to-provide-a-router-navigate-function-in-angular-2-project