4

我怎样才能将这些与可观察的结合为一个?它们具有相同的功能。

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

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

1 回答 1

7

您可以使用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 将是具有属性名称作为参数名称和值作为值的对象。所以对于一条路线:

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

带参数

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

allParams 将是

{ 
  params: { 
     id: "paramvalue" 
    },
  qparams: { 
     qparam: "qpvalue" 
    } 
 }
于 2017-08-02T04:26:24.927 回答