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

查看:20
本文介绍了如何在 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天全站免登陆