问题
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