簡體   English   中英

如何等到翻譯數組循環完成 - 使用訂閱

[英]How to wait until translation array loop complete - with subscribe

這是我的翻譯方法。 在控制台上獲取空數組。 如何處理這個?

 headersTranslator(headers) {
    const transHeader: any[] = [];
    headers.map((header) => {
        this.translate.get(header.title).subscribe((value) => {
            if (!value) return;
            transHeader.push({ ...header, title: value });
        });
    });
    console.log('transHeader', transHeader);
    return transHeader;
}

我的嘗試:由於在循環下放置了 observable,所以發現具有挑戰性。

 headersTranslator(headers) {
    const transHeader: any[] = [];
    return new Promise((resolve, reject) => {
        headers.map((header) => {
            this.translate.get(header.title).subscribe({
                next: (value) =>
                    transHeader.push({ ...header, title: value }),
            });
        });
        resolve(transHeader);
    });
}

您需要使用諸如forkJoin類的運算符將一組可觀察對象轉換為單個可觀察對象,該可觀察對象返回這些底層可觀察對象的結果數組

對於異步版本,請使用firstValueFromlastValueFrom

async function headersTranslator(headers) {
    const observables = headers.map(header =>
                                    this.translate.get(header.title)
                                    .pipe(map(value => ({ ...header, title: value }))));
    return await lastValueFrom(forkJoin(observables));       
}

或者,如果您希望 function 返回可觀察對象並訂閱它:

function headersTranslator(headers) {
    const observables = headers.map(header =>
                                    this.translate.get(header.title)
                                    .pipe(map(value => ({ ...header, title: value }))));
    return forkJoin(observables);       
}

我試過了,它有效。

async headersTranslator(headers) {
    const transHeader: any[] = [];
    return new Promise((resolve, reject) => {
        headers.map((header, i) => {
            this.translate
                .get(header.title)
                .subscribe({
                    next: (value) =>
                        transHeader.push({ ...header, title: value }),
                })
                .add(() => {
                    if (headers.length === i + 1) {
                        resolve(transHeader);
                    }
                });
        });
    });
}

但是正在尋找一種標准的方法來獲得它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM