[英]Angular 2 Routes not behaving as expected
我正在尝试使用参数实现基本路由,模仿Heroes示例( https://angular.io/docs/ts/latest/guide/router.html )。 我的AppModule声明了一个路径:
const appRoutes: Routes = [
{ path: '', component: AllStuffComponent },
{ path: 'stuff/:id', component: SingleStuffComponent },
];
我的SingleStuffComponent看起来如下,只是为了测试其机制:
export class SingleGuiComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router,
) {}
ngOnInit() {
this.route.params
.switchMap((params: Params) => params['id'])
.subscribe((id: any) => console.info("ID=" + id));
}
}
我尝试在浏览器http://localhost:3000/stuff/2345
执行URL。 但是在调试器中,我看到了:
ID=2
ID=3
ID=4
ID=5
为什么会这样呢? 我只希望ID=2345
的单个控制台日志。
我认为您应该尝试并且仅使用map()函数提取ID,它将起作用。
this.route.params
.map((params: Params) => params['id'])
.subscribe((id: any) => console.info("ID=" + id));
您将主要使用switchMap()从map()获取发出的ID,并将其用于新的API调用或类似的操作,这样您就不必嵌套2个订阅函数。
例:
this.route.params
.map((params: Params) => params['id'])
.switchMap(id => this._someService.getSomething(id))
.subscribe((result: any) => {
console.log(result);
});
如果没有switchMap(),则必须执行以下操作:
this.route.params
.map((params: Params) => params['id'])
.subscribe((id) => {
this._someService
.getSomething(id)
.subscribe(result => this.result = result);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.