[英]Combine two RxJS Observables/Subscriptions and iterate through their data
我使用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
...
}
}
});
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.