Angular - 结合params和queryParams observables

时间:2017-08-02 04:16:44

标签: angular angular-observable

如何将这些与可观察者合并为一个?它们具有相同的功能。

this.sub = this.route.params.subscribe((params: any) => {
    // functionality
});

this.sub = this.route.queryParams.subscribe((params: any) => {
    // same functionality   
});

1 个答案:

答案 0 :(得分:5)

您可以使用combineLatest执行此操作:

import { ActivatedRoute } from '@angular/router';

import { combineLatest } from 'rxjs';

// ...

class MyComponent {

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {

    const params = this.route.params;
    const queryParams = this.route.queryParams;

    combineLatest(params, queryParams, (params, qparams) => ({ params, qparams }))
      .subscribe(allParams => console.log(allParams.params, allParams.qparams));
  }

}

params和qparams将是具有属性名称作为param名称且值为值的对象。所以对于一条路线:

 RouterModule.forRoot([{
  path: 'test1/:id',
  component: Test1Component
}])

与params

http://localhost:4200/test1/paramvalue?qparam=qpvalue

allParams将

{ 
  params: { 
     id: "paramvalue" 
    },
  qparams: { 
     qparam: "qpvalue" 
    } 
 }