Angular 2路由行为不如预期
问题描述:
我试图用参数实现基本路由,模仿英雄示例(https://angular.io/docs/ts/latest/guide/router.html)。我的AppModule声明的路径:Angular 2路由行为不如预期
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()从地图()获取发射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);
});
+0
是的!这工作。虽然,我很困惑为什么Angular的Hero例子(hero-details.component.ts)有switchMap()。 –
你有没有尝试删除'switchMap'功能,并获得了'PARAMS [ '身份证']在'subscribe'函数里面? 我怀疑'switchMap'将字符串分割为单个字符 –