【问题标题】:Angular get route params with switchMap not working [duplicate]带有switchMap的角度获取路由参数不起作用[重复]
【发布时间】: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

标签: angular routes rxjs


【解决方案1】:

您需要订阅以评估 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();

【讨论】:

    【解决方案2】:

    //this will work
    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
      })
    ).subscribe(item=>{
    console.log(item
    })

    【讨论】:

    • 订阅会让你看到最终结果,如果你想检查管道中的值,你可以在参数中使用 console.log(),但是你所有的逻辑都将进入管道,订阅可观察的就是“执行”它本身
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    相关资源
    最近更新 更多