How to provide a router navigate function in Angular 2 project

耗尽温柔 提交于 2019-12-25 07:26:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!