问题:我的应用可能会收到查询字符串参数,并且根据查询字符串中的哪个参数,需要执行不同的操作:
1)我在querystring中查找广告客户,如果存在,我需要订阅一项验证广告客户的服务:
this.activatedRoute.queryParams
.filter(data => data.hasOwnProperty('advertiser'))
.mergeMap(v => {
advertiserId = v.advertiser;
return this.myService.advertiserCheck(v.advertiser);
})
.subscribe(data => {
if (true === data.valid) {
// some processing takes place
}
});
2)我在这里寻找 orderKey param:
this.activatedRoute.queryParams
.filter(data => data.hasOwnProperty('orderKey'))
.mergeMap(() => this.activatedRoute.firstChild.firstChild.url)
.subscribe(segments => {
// some processing takes place with the url segments
});
如您所见,我订阅了两次ActivatedRoute.queryParams。有没有办法可以结合2?我尝试了以下方法:
this.activatedRoute.queryParams
.filter(data => data.hasOwnProperty('advertiser') || data.hasOwnProperty('orderKey'))
.mergeMap(v => {
if (v.hasOwnProperty('advertiser')) {
advertiserId = v.advertiser;
return this.myService.advertiserCheck(v.advertiser);
} else {
return this.activatedRoute.firstChild.firstChild.url;
}
})
.subscribe(data => {
console.log('which one am I handling?');
});
这些参数不会同时出现在查询字符串中,但在订阅中我不知道我正在处理哪一个。我想我可以创建一个变量,然后在订阅中检查它,但它看起来不是很优雅。有没有更好的办法?我应该离开,因为它不那么令人困惑吗?
答案 0 :(得分:1)
我会把它们留作2个独立的序列,因为它们有不同的最终结果。但我也希望它们与shareReplay
运算符共享相同的基础可观察序列。
ngOnInit(){
this.obs$ = this.activatedRoute.queryParams
.shareReplay();
// sequence 1
this.obs$
.filter(data => data.hasOwnProperty('advertiser'))
.mergeMap(v => {
advertiserId = v.advertiser;
return this.myService.advertiserCheck(v.advertiser);
})
.subscribe(data => {//process});
// sequence 2
this.obs$
.filter(data => data.hasOwnProperty('orderKey'))
.mergeMap(() => this.activatedRoute.firstChild.firstChild.url)
.subscribe(segments => {//process});
}