我使用Angular(版本7)和RxJS并进行两次api调用,每次调用返回一个observable,然后我订阅。
现在我必须组合这些订阅,因为来自两个observable的数据是相互依赖的,我需要它们来实现某些功能(例如,一个过滤器检查从subcription2接收的id是否出现在subscription1中,然后只返回一些东西......)。
由于我的代码很长,我已经准备了一个较小的样本版本并标记了重要的地方给我评论:
getSomething(){
/**
* anIdFromSubscriptionTwo: An id that I need from subscription2
*/
const subscription1 = this.service.getSomeStuff().subscription((someStuff) => {
this.someStuff = stuff;
this.someStuff.forEach((stuff) => {
if(stuff.someProperty !== null && stuff.id === anIdFromSubscriptionTwo){
...
}
});
}
/**
* aIdFromSubscriptionOne: An id of type string that I get in the forEach loop inside of subscription1
* aTypeFromSubscriptionOne: A type of type string that I get in the forEach loop inside of subscription1
*/
const subscription2 = this.service.getSomeOtherStuff(aIdFromSubscriptionOne: string, aTypeFromSubscriptionOne: string).subscription((someOtherStuff) => {
this.someOtherStuff = someOtherStuff;
this.someOtherStuff.forEach(() => {
// This is the only if statement I need, after combining the two subscriptions
if(subscription1.stuff.someProperty !== null && subscription1.stuff.id === someOtherStuff.id){
const properties: Image = {
id: // an id I need from subscription1
class: // a class I need from subscription1
type: // a type I need from subscription2
ref: // a reference to the image url from subscription2
...
}
}
})
});
}
如何组合这两个订阅,以便我可以在forEach循环中访问它们的数据并进行比较或一般使用?
你使用switchMap来避免在另一个内部订阅
import { switchMap } from 'rxjs/operators';
this.service.getSomeStuff().pip(switchMap((someStuff) => {
this.someStuff = someStuff;
this.service.getSomeOtherStuff(aIdFromSubscriptionOne: string, aTypeFromSubscriptionOne: string)
).subscribe((someOtherStuff) => {
this.someOtherStuff = someOtherStuff;
this.someOtherStuff.forEach(() => {
// make a foreach loop here on someStuff to check if someOtherStuff exist in some Stuff
this.someStuff.foreach((somestuff) => {
if(somestuff.someProperty !== null && somestuff.id === someOtherStuff.id){
const properties: Image = {
id: // an id I need from subscription1
class: // a class I need from subscription1
type: // a type I need from subscription2
ref: // a reference to the image url from subscription2
...
}
}
});
});
});
});