angular - 在 Angular 2 中订阅路由参数和查询参数

标签 angular rxjs

我设置了以下路由系统

export const MyRoutes: Routes = [
  {path: '', redirectTo: 'new', pathMatch: 'full'},
  {path: ':type', component: MyComponent}
];

并拥有以下导航系统

goToPage('new');
goToPageNo('new', 2);

goToPage(type) {
  this.router.navigate([type]);
}
goToPageNo(type, pageNo) {
  this.router.navigate([type], {queryParams: {page: pageNo}});
}

示例 URL 如下所示

http://localhost:3000/new

http://localhost:3000/new?page=2

http://localhost:3000/updated

http://localhost:3000/updated?page=5

有时他们有可选查询参数(页面)

现在我需要读取路由参数和查询参数

ngOnInit(): void {
  this.paramsSubscription = this.route.params.subscribe((param: any) => {
    this.type = param['type'];
    this.querySubscription = this.route.queryParams.subscribe((queryParam: any) => {
      this.page = queryParam['page'];
      if (this.page)
        this.goToPageNo(this.type, this.page);
      else
        this.goToPage(this.type);
    })
  })
}

ngOnDestroy(): void {
  this.paramsSubscription.unsubscribe();
  this.querySubscription.unsubscribe();
}

现在这没有按预期工作,访问没有 queryParams 的页面可以工作,然后我访问带有 queryParams 的页面“goToPageNo”被多次调用,因为我在路由参数中订阅 queryParams。

我查看了 Angular 2 文档,他们没有任何示例或代码可以同时实现对路由参数和查询参数的订阅。

有什么办法可以正确地做到这一点?有什么建议吗?

最佳答案

通过在订阅前使用 Observable.combineLatest 组合可观察对象,我设法获得了对 queryParams 和 Params 的单一订阅。

例如。

var obsComb = Observable.combineLatest(this.route.params, this.route.queryParams, 
  (params, qparams) => ({ params, qparams }));

obsComb.subscribe( ap => {
  console.log(ap.params['type']);
  console.log(ap.qparams['page']);
});

关于angular - 在 Angular 2 中订阅路由参数和查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40699229/

相关文章:

angular - 使用 Angular 中的自定义按钮进行滑动分页/导航

angular - ts1206 装饰器在这里无效,Angular 6 教程示例

rxjs - 为什么 withLatestFrom RxJS 方法不是静态的?

node.js - 如何修复导出 'NotificationKind' 中未找到 'rxjs' 错误

javascript - 在 Angular 中使用 debounceTime

node.js - 在基于 Angular 6 的项目中更新 npm 时出现错误

测试运行时 Angular 2 模板解析错误

rxjs - 如何在 RxJS 中做不同的 throttle

javascript - RxJS:如何在传递下一个有效值之前进行一些清理?

使用 trackby 的 Angular Drag and Drop 正在迅速恢复