Angular使用switchMap获取路线参数不起作用

时间:2019-07-17 21:16:39

标签: angular routes rxjs

我正在尝试按照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语句正常工作。

2 个答案:

答案 0 :(得分:1)

//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
})

答案 1 :(得分: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();