【发布时间】:2017-05-14 21:48:27
【问题描述】:
下面的代码描述了我的 Angular 2 应用程序中的路由
RouterModule.forRoot( [
{path:'' , component:HomeComponent},
{path:'acategories/:id/products/:pid' , component:ProductComponent},
{path:'acategories/:id/products' , component:ProductsComponent},
{path:'acart' , component:CartComponent},
{path:'about' , component:AboutComponent},
{path:'aorders' , component:OrderDetailsComponent},
{path:'asearch' , component: ProductSearchComponent},
{path:'**',component:PageNotFoundComponent}
])
我的根组件具有指向这些路由的链接,如下图所示
用户通过在文本框中输入文本并单击搜索按钮来搜索项目。一旦用户单击“搜索”,以下方法 在根组件中将被执行,它基本上导航到“asearch”路线。
onSearch()
{
if(this.formGroup.valid)
{
this.router.navigate(['asearch' , {search:this.formGroup.controls['search'].value}]);
}
}
现在我面临的问题是,当“asearch”路线已经处于活动状态[即它当前的活动路线”] 并且用户尝试 搜索项目,结果不显示。
下面是 ProductSearchComponent 中从服务器获取结果的代码。
ngOnInit() {
console.log('ngOnInit()');
this.route.params.subscribe( (params) => {
this.search = params['search'];
})
this.service.searchProducts(this.search).subscribe( {
next: (data) => {
this.products = data;
},
error: (err) => { this.toaster.error(err) }
})
}
【问题讨论】:
-
如果不看是什么代码导致这些结果显示出来就很难判断。
-
@Günter Zöchbauer,将更新我的问题
-
如果没有像
{path:'asearch/:id' , component: ProductSearchComponent}这样的路径,它甚至可以工作吗? -
确保将
pathMatch: 'full'用于没有重定向且没有子路由的空路径路由{path:'' , component:HomeComponent, pathMatch: 'full'}, -
现在我观察到的是,如果“asearch”已经是活动路由,那么 ngOnInit() 没有执行
标签: angular