[英]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. 在我的Angular 2项目中,我有一个自定义函数
goToObject(objectType:string, objectID: number)
,可用于在应用程序中的几个不同组件中导航到不同对象。 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. 然后将其提供给根组件,然后将其注入到要使用的位置并调用其方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.