使用 angular 路由参数而不订阅它

Use angular route params without subscribing to it

我正在编写一个简单的 UI 应用程序,我需要调用 API 以在产品详细信息组件中通过 id 获取产品。我从路由参数中得到的 ID

通常,我会这样做:

this.activatedRoute.params
   .subscribe(params => {
     if (params['primaryKey']) {
       this.service.get(params['primaryKey'])
         .subscribe(product => {
           this.product = product;
         });
     }
   });

它工作正常,只是这些订阅树看起来有点难看。我想使用更多的 RxJS,所以它看起来像这样(控制台日志只是为了演示):

this.product$ = this.activatedRoute.params
  .pipe(filter(params => {
       console.log('in filter', params);
       return 'primaryKey' in params;
     }),
     map(params => {
       console.log('in map', params);
       return parseInt(params.primaryKey, 10);
     }),
     switchMap(primaryKey => {
       console.log('in switch map', primaryKey);
       return this.service.get(primaryKey);
     }));

但直到我最终订阅它,它才以这种方式工作(它甚至不触发任何控制台日志)...为什么?

如果您想从您创建的流中获取价值,您需要在最后订阅。除非你这样做,否则它不会起作用。另一种方法是在 product$ 的模板中使用异步管道。

您从一个 Observable 开始,然后通过一些函数(过滤、映射等)。

但是,在您调用 subscribe() 之前,您不会开始观察它并收集值。您可以将所有逻辑移动到该函数内部或将其提取到 RxJS 运算符,但最后仍然是该函数:

this.product$ = this.activatedRoute.params
  .pipe(...)
  .subscribe();

您可以在 subscribe function 上的文档中找到更多信息。

通过使用 pipe 应用各种运算符,您可以在现有运算符的基础上创建新的 Observable,也就是说必须对发出的结果应用附加函数。

但是在创建第一个 Subscription 之前它不会发出值。

无需订阅的解决方案

您可以通过以下方式获取路由参数:

this.route.snapshot.paramMap.get('id')

route 的类型是 ActivatedRoute

  constructor(
    private route: ActivatedRoute,
  ) { }

可能的解决方案之一是

this.route.queryParams.<QUERY_PARAM>

route 必须是 ActivatedRouteSnapshot

类型