如何在Angular 2项目中提供路由器导航功能 [英] How to provide a router navigate function in Angular 2 project

查看:61
本文介绍了如何在Angular 2项目中提供路由器导航功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 2项目中,我有一个自定义函数goToObject(objectType:string, objectID: number),可用于导航到应用程序中几个不同组件中的不同对象.该函数如下所示:

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?

推荐答案

您可以使用共享服务

@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.

这篇关于如何在Angular 2项目中提供路由器导航功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆