如何在 Angular 中从 url 获取数据 7
how to get data from url in Angular 7
我在 angular 中使用了 One component For many page。
我想从每个组件发送一个参数以显示任何不同的数据。
所以我使用此代码调用 Html:
中的每个组件
<a [routerLink]="['categories']" >Page1</a>
<a [routerLink]="['categories']" >Page2</a>
现在在路由中我使用了这个代码
{path:'Page1' ,component : ProductCategoriesPagesComponent ,data : {PageNo : 1}},
{path:'Page2' ,component : ProductCategoriesPagesComponent,data : {PageNo : 2}}
然后我在 ProductCategoriesPagesComponent
中使用了这段代码
ngOnInit() {
this.route.data
.subscribe(data => {
console.log("data",data);
});
}
但我明白了
data {}
在控制台中。
请帮助我如何从路由中获取参数
如果我弄错了,请显示此方法的最佳方法。
谢谢。
您可以通过访问路由的快照来访问数据,如下所示:
this.route.snapshot.data['PageNo'];
因此您可以执行上述操作而不是订阅可观察对象
您需要注入 ActivatedRoute
并从快照中获取数据。
this.activatedRoute.snapshot.data['PageNo'];
我在 angular 中使用了 One component For many page。 我想从每个组件发送一个参数以显示任何不同的数据。 所以我使用此代码调用 Html:
中的每个组件<a [routerLink]="['categories']" >Page1</a>
<a [routerLink]="['categories']" >Page2</a>
现在在路由中我使用了这个代码
{path:'Page1' ,component : ProductCategoriesPagesComponent ,data : {PageNo : 1}},
{path:'Page2' ,component : ProductCategoriesPagesComponent,data : {PageNo : 2}}
然后我在 ProductCategoriesPagesComponent
中使用了这段代码ngOnInit() {
this.route.data
.subscribe(data => {
console.log("data",data);
});
}
但我明白了
data {}
在控制台中。 请帮助我如何从路由中获取参数 如果我弄错了,请显示此方法的最佳方法。 谢谢。
您可以通过访问路由的快照来访问数据,如下所示:
this.route.snapshot.data['PageNo'];
因此您可以执行上述操作而不是订阅可观察对象
您需要注入 ActivatedRoute
并从快照中获取数据。
this.activatedRoute.snapshot.data['PageNo'];