gpt4 book ai didi

Angular 获取路由参数,switchMap 不起作用

转载 作者:行者123 更新时间:2023-12-03 08:53:53 28 4
gpt4 key购买 nike

我正在尝试按照 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 根据路由参数的值有条件地调用其他可观察对象。但是,我什至无法让第一个 switchMap 语句正常工作,如上所示。

最佳答案

您需要订阅以评估 Observable 并根据参数有条件地调用另一个 observable,如下所示:

import { switchMap } from 'rxjs/operators';

this.getRouteParams$ = this.route.params.pipe(
switchMap(params => {
console.log(params);
// How to check params here and then subscribe to other observables conditionally
//here you can check the params and return the another observable like this:

//BELOW code is just to show how to return another observable conditionally
//Change it as per your logic
const p = params['id']; //i am assuming that your param name is `id`;
if(p === 100) {
return this.anotherObservable()
.pipe(
tap(r => {
//DO whaterver you want to do with the response of the observable
console.log(r);
})
);
} else {
return of(someThingAsPerYourLogic);
}
})
).subscribe();

关于Angular 获取路由参数,switchMap 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57084163/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com