【发布时间】:2019-07-17 21:16:39
【问题描述】:
我正在尝试按照Angular Routing 文档中有关如何获取路由参数的教程进行操作。
使用subscribe时可以获取路由参数。
this.getRouteParams$ = this.route.params.subscribe(params => {
// Works
console.log(params);
});
但是根据文档,最好使用 switchMap。我无法让 switchMap 示例在我的代码中工作,我不知道为什么。
import { switchMap } from 'rxjs/operators';
this.getRouteParams$ = this.route.params.pipe(
switchMap(params => {
// Does not work
console.log(params);
// How to check params here and then subscribe to other observables conditionally
})
);
最终目的是在收到并验证后,使用switchMap根据路由参数的值有条件地调用其他observable。但是,我什至无法让第一个 switchMap 语句正常工作,如上所示。
【问题讨论】:
-
您仍然需要在某个地方订阅(或通过管道传输到异步),并且在您有另一个可观察的展开之前使用 switchMap 是没有意义的。
-
这种场景最好使用
mergeMap