我正在嘗試literalsService使用管道從 observables 陣列(每個從 中獲得)執行和獲取值。這是代碼:
translateLiterals() {
const literalsToTranslate: string[] = [
'certificate_title',
'with_address',
'hereby',
'declare',
'electronic_records',
'proceeded_to_shipment',
'return_address',
'return_address',
'addressee',
'message_subject',
];
const newArray: Observable<string>[] = [];
literalsToTranslate.map(literal => newArray.push(this.literalsService.getValue('Ngwa.Ngwa', literal)));
this.literalsArray$ = forkJoin([...newArray]).pipe(map((results) => {
console.log(results);
return results;
}));
}
當然,我訂閱了 html 端的管道:
<ng-container *ngIf="literalsArray$ | async"></ng-container>
但從console.log()不列印任何東西......有人知道為什么嗎?
uj5u.com熱心網友回復:
可能this.literalsService.getValue('Ngwa.Ngwa', literal);回傳字串。如果是這種情況,您需要使用以下命令將其轉換為 Observable:
of(this.literalsService.getValue('Ngwa.Ngwa', literal));
還forkJoin等待所有給定的流完成,然后發出值。
uj5u.com熱心網友回復:
正如用戶@ShamPooSham 和@martin 在評論中所說的那樣,問題在于該方法this.literalsService.getValue ('Ngwa.Ngwa', literals)正在觀察文字的變化,并且forkJoin由于文字未完成,該方法從未啟動。我創建了一個單獨的方法來解決這個問題,并take在初始方法中添加了一個:
新方法:
translateString(text: string): Observable<string> {
return this.literalsService.getValue('Ngwa.Ngwa', text).pipe(
switchMap((translated) => {
if (!translated.startsWith('N/A')) {
return of(translated);
} else {
return this.literalsService.getValue('Ngwa.Ngwa', text).pipe(
skip(1), // First event translation comes not translated
map((secondTryTranslation) => {
return secondTryTranslation;
}));
}
}),
);
}
第一種方法的修正:
translateLiterals() {
const literalsToTranslate: string[] = [
'certificate_title',
'with_address',
'hereby',
'declare',
'electronic_records',
'proceeded_to_shipment',
'return_address',
'return_address',
'addressee',
'message_subject',
];
const newArray: Observable<string>[] = [];
literalsToTranslate.map(literal => newArray.push(this.translateString(literal).pipe(take(1)))); //<--- Here is the correction
this.literalsArray$ = forkJoin([...newArray]).pipe(map((results) => {
return results;
}));
}```
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383505.html
上一篇:等待IIFE結果與單獨的異步函式
