Angular - Combine params and queryParams observables

我只是一个虾纸丫 提交于 2019-12-06 08:22:33

问题


How can I combine these to observables into one? They have the same functionality.

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

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

回答1:


You can use combineLatest to do that:

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 and qparams will be objects with the property name as the param name and the value as the value. So for a route:

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

with params

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

allParams will be

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


来源:https://stackoverflow.com/questions/45451389/angular-combine-params-and-queryparams-observables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!