我有一个Angular网站,它有几个组件。其中许多组件包括显示链接到其他组件的文本。我用这样的html元素路由到这些其他组件:
<a (click)='routeToTeamSeason(team_season_id)' [routerLink]>{{team}}</a>
然后函数看起来像:
routeToTeamSeason(team_season_id: string): void{
console.log("Routing to: " + team_season_id)
this.router.navigate(['/teams/season', team_season_id])
}
其中router是@angular/router类的一个实例。
我的几个组件都可以使用相同的路由逻辑,现在我有相同的功能复制并粘贴到每个组件的.ts文件中。如何创建一个共享函数,该函数将被每个组件的html模板识别?
不确定这是最好的方法,但这是我找到的解决方案:
创建一个单独的文件route-to-team-season.ts:
export function routeToTeamSeason(team_season_id: string): void{
console.log("Routing to: " + team_season_id)
this.router.navigate(['/teams/season', team_season_id])
}
然后将该函数导入任何组件并在本地声明:
myRouteToTeamSeason = routeToTeamSeason
最后,更新模板以调用myRouteToTeamSeason(...)
这对我来说似乎有点难看,所以如果有人有更好的解决方案,请告诉我!