Javascript 角度2路由的行为不符合预期
我正试图用参数实现基本路由,模仿Heroes示例()。My AppModule声明一个路径:Javascript 角度2路由的行为不符合预期,javascript,angularjs,typescript,Javascript,Angularjs,Typescript,我正试图用参数实现基本路由,模仿Heroes示例()。My AppModule声明一个路径: const appRoutes: Routes = [ { path: '', component: AllStuffComponent }, { path: 'stuff/:id', component: SingleStuffComponent }, ]; 我的SingleStuff组件如下所示,只是为了测试力学: export class SingleGuiCompon
const appRoutes: Routes = [
{ path: '', component: AllStuffComponent },
{ path: 'stuff/:id', component: SingleStuffComponent },
];
我的SingleStuff组件如下所示,只是为了测试力学:
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
。但在调试器中,我看到:
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个subscribe函数
例如:
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);
});
您是否尝试删除
switchMap
函数,并在subscribe
函数中获取params['id']
?我怀疑switchMap
会将字符串拆分为单个字符ep!成功了。尽管如此,我还是不明白Angular的Hero示例(Hero details.component.ts)为什么有switchMap()。