我创建了一个角度应用程序,我将“欢迎页面”组件设置为默认路由,因此它是第一个在用户访问该站点时弹出的组件。在该组件中,我有链接需要激活app组件中的router-outlet
。看到“欢迎页面组件”被路由器插座拉入,我认为我必须使用服务来检测点击的链接并更新应用程序组件中的路由,因为两个组件之间没有任何明确的通过它除此以外。
我创建了一个看起来像这样的服务文件
@Injectable()
export class RouteService{
public clickedLink: Subject<string> = new Subject<string>();
setLink(link: string){ this.clickedLink.next(link); }
}
我将“欢迎页面组件”修改为这样
export class WelcomePageComponent {
constructor(private RS: RouteService ){}
sendLink(link: string){ this.RS.setLink(link); }
}
然后将模板中的链接修改为此
<a (click)="sendLink('/illustration')"></a>
然后在app组件中我有这个
export class AppComponent implements OnInit {
pageLink: string;
constructor( private RS: RouteService, private router: Router ){}
ngOnInit(){
this.RS.clickedLink.subscribe(link => this.pageLink = link);
}
pageNav(link:string){ this.router.navitgate(link); }
}
现在我一直在搞清楚如何触发pageNav()
函数来更新路线。我试着听@HostListener
试图听pageLink
变量和一点点可观察量,但似乎找不到任何与我想要实现的相关的东西。有人能帮忙吗?
UPDATE
我的app.module
看起来像这样
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
PagesModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
PagesModule
是我为“页面组件”启动的模块,看起来像这样
@NgModule({
imports: [ BrowserModule ],
declarations: [
WelcomePageComponent, IllustrationPageComponent
],
exports: [
WelcomePageComponent, IllustrationPageComponent
]
})
export class PagesModule{}
AppRoutingModule
看起来像这样
export const routes: Routes = [
{ path: '', redirectTo: '/welcome', pathMatch: 'full' },
{ path: 'welcome', component: WelcomePageComponent },
{ path: 'illustration', component: IllustrationPageComponent }
]
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
您可以通过以下步骤解决问题:
this.RS.clickedLink.subscribe(link => { this.pageNav(link); });
this.router.navigate([link]);
我不确定如果我完全理解你的问题,但角度路由非常容易配置和实现。只需将routerLink
指令添加到任何元素,它将在单击时更新路由器插座。这是一个例子
<nav>
<a routerLink="/dashboard">
dashboard
</a>
<a routerLink="/path-to-another-component">
new componenet
</a>
</nav>
路由器链接指令调用场景后面的角度路由服务,检查路由器配置是否找到要呈现的组件并更新路由器插座。
这里没有必要观察。我希望能帮助你。