Как исправить вложенную подписку, чтобы она работала последовательно?
Я пытаюсь подписаться несколько раз на свой бэкэнд. Пока мой код извлекает данные, кажется, что-то работает неправильно. При выполнении следующего кода все отображается так, как должно быть, кроме последовательности. Таким образом, мои учетные записи выбираются в правильной последовательности, но мои транзакции иногда происходят в неправильном порядке.
Мой код:
for(var i = 0; i < this.userlength; i++) {
//fetch transactions data of the account with index "countul" to our local storage
this.getAccounts(this.as.getUserId(), countul)
.pipe(map(accountData => {
return {
accounts2: accountData.accounts.map(account => {
return {
productDescription: account.productDescription,
balance: account.currentBalance,
iban: account.iban
};
})
};
})
//If an error at requesting data from external bank occurs, delete every token
)
.subscribe(transformedTransactionData => {
this.accounts[countul] = transformedTransactionData.accounts2;
for(var j = 0; j < this.accounts[countul].length; j++) {
//Printing some things to the console for testing purpose
console.log("countacc: "+countacc);
console.log(this.accounts[countul][countacc].iban);
//fetch transactions data of the useraccount with index "countul" and subaccount with index "countacc" to our local storage
(this.getTransactions(this.transactionsPerPage, this.currentPage, this.accounts[countul][countacc].iban, countul, this.as.getUserId()))
.pipe(map(transactionData => {
return {
transactions2: transactionData.transactions.map(transaction => {
return {
date: transaction.bookingDate,
receiver: transaction.counterPartyName,
amount: transaction.amount,
mandateReference: transaction.mandateReference,
id: transaction.paymentIdentification,
purpose: transaction.paymentReference
};
})
};
}))
.subscribe(transformedTransactionData => {
this.transactions[countacc2] = transformedTransactionData.transactions2;
//Stop loading spinner
this.isLoading = false;
setTimeout(() => {}, 2000);
console.log("Transactions of account " +countacc2 + ": "+JSON.stringify(this.transactions[countacc2]));
console.log("Transactions of account " +countacc2 + ": "+JSON.stringify(this.transactions[countacc2]));
countacc2++;
}), error => {
console.log('There was an error getting data');
return Observable.throw(error);
};
//Go to the possible subaccount
countacc++;
}
//Go to the next bankaccount
countul++;
}), error => {
console.log('There was an error getting data');
return Observable.throw(error);
};
}
}
методы "getTransaction" и "getAccounts":
//Get account data of bankaccount with index (if there are more than one bank account integrated)
getAccounts(userid: string, index: number) {
//DataSchema for the http request
const data = {userid, index};
//Making a HTTP Request to our Backend with sending out userid and the index of the bankaccount we want
return this.http.post<{message: string; accounts: any}>(this.apiUrl + "/get", data);
}
//Get transaction data of account with index of chosen bankaccount and the iban (if there is a subaccount)
getTransactions(transactionsPerPage: number, currentPage: number, iban: string, index:number, userid: string) {
//Making a HTTP Request to our Backend with sending out iban of account, index of bakaccount and our userid
return this.http.post<{transactions: any}>(this.apiUrl + "/transactions", {iban, index, userid});
}
Так что иногда это выглядит так:
Аккаунт 1 - "имя", "второе имя" - Операции с аккаунтом 2-
Аккаунт 2 - "имя", "второе имя" - Операции с аккаунтом 1-
Я должен отметить, что иногда это показано в правильной последовательности.
Может ли кто-нибудь помочь мне исправить мой код?
1 ответ
Вы можете комбинировать наблюдаемые как это
let observable1 = this.http.get('apiURL1').map(res => res.json());
let observable2 = this.http.get('apiURL2').map(res => res.json());
Observable.forkJoin([observable1 , observable2 ]).subscribe(results => {
// results[0] is our observable1
// results[1] is our observable2
});