I have a UI form that to update or add translation text.
I would need to write rxjs statement to fulfill the following:
Fire httpGet to database to get translations of multiple languages
Loop the list of translations.
If my UI fields matches translations from httpGet, I would need to do a series of httpPut to update them in database. Example: I filled in Spanish translation in UI, if my httpGet returns results including Spanish, I would need to HttpPut to update Spanish record in database.
If my UI fields does not exist in translations from httpGet, I would need to do a series of httpPost to update them in database. Example: I filled in Chinese translation in UI, if my httpGet does not return any Chinese result, I would need to httpPost to add Chinese record in database.
I written the first part, but understand that rxjs is not sequential and cannot write a subscribe in another subscribe, I cannot write it in this way.
p/s: My httpGet returns me x, in which has the structure of x.dataCount and x.dataSet. x.dataCount is number of translation object. x.dataSet is an array of translation objects.
How do I write the rxjs statement for this? Any clue?
this.GetTranslations(group).subscribe(x => {
x.dataSet.forEach(translation => {
switch (translation.Language) {
case chineseCode:
if (chineseInUI){
chineseExist = true;
let newChinese = {
"Id": translation.Id,
"Language": translation.Language,
"PhraseKey": translation.PhraseKey,
"PhraseValue": chineseInUI,
}
this.webApiService.httpPut$(this.resourceApiService.getURL('translationmanagerURL') + translation.Id, newChinese).subscribe(); }
break;
case spanishCode:
if (spanishInUI){
let newSpanish = {
"Id": translation.Id,
"Language": translation.Language,
"PhraseKey": translation.PhraseKey,
"PhraseValue": spanishInUI
}
this.webApiService.httpPut$(this.resourceApiService.getURL('translationmanagerURL') + translation.Id, newSpanish).subscribe();
}
break;
}
});
});
You can do it like this using operators
mergeMap to create an array of observablesmergeAll to get the values of the inner observables in the subscription this.GetTranslations(group)
.pipe(
mergeMap((x) => {
return x.dataSet.map((translation) => {
switch (translation.Language) {
case chineseCode:
if (chineseInUI) {
chineseExist = true;
let newChinese = {
Id: translation.Id,
Language: translation.Language,
PhraseKey: translation.PhraseKey,
PhraseValue: chineseInUI,
};
return this.webApiService.httpPut$(
this.resourceApiService.getURL('translationmanagerURL') +
translation.Id,
newChinese
);
}
break;
case spanishCode:
if (spanishInUI) {
let newSpanish = {
Id: translation.Id,
Language: translation.Language,
PhraseKey: translation.PhraseKey,
PhraseValue: spanishInUI,
};
return this.webApiService.httpPut$(
this.resourceApiService.getURL('translationmanagerURL') +
translation.Id,
newSpanish
);
}
break;
}
return EMPTY;
});
}),
mergeAll()
)
.subscribe((response) => {
console.log('response', response);
});