简体   繁体   中英

How to provide a router navigate function in Angular 2 project

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM