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

标签 angular rxjs angular-ui-router

我正在编写一个简单的 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);
     }));

但在我最后订阅它之前它不会以这种方式工作(它甚至不会触发任何控制台日志)...为什么?

最佳答案

没有订阅的解决方案

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

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

route 是类型 ActivatedRoute

  constructor(
    private route: ActivatedRoute,
  ) { }

关于angular - 使用 Angular 路由参数而不订阅它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56977235/

相关文章:

javascript - Controller 中ui-router的一个参数并解析

angularjs - Angular ng-submit 没有触发所需的 Controller 方法

html - 使用垫子按钮以 Angular 构建导航栏

javascript - Angular 2 Webpack 2 - Sass 在组件中不起作用

javascript - 为什么 RxJS 中没有调用所有订阅者

angular - @ngrx/effect 中止 Angular 应用程序中的多个 REST 调用

angular - 嵌套数组的 RXJS 运算符

html - Angular 占位符图像和文本

angular - 如何在 OnDestroy 中完成事件的 debounceTime

javascript - Angular 2.4.0 路由器 : Named route. 错误:无法匹配任何路由