我正在尝试创建一个将文本翻译成其他语言的 Angular 自定义管道。所有数据都是动态的。
这是我的服务:
import { Http } from "@angular/http";
import { Injectable } from "@angular/core";
import { Observable, of } from "rxjs";
import { map, filter, switchMap, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { environment } from '../../../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class TranslationService {
constructor(private http: HttpClient,
private router: Router) {
}
translateRequest(word?): Observable<any>{
let key = environment.yandexKey;
return this.http
.get(`https://translate.yandex.net/api/v1.5/tr.json/translate?key=${key}&text=${word}&lang=en-fr`)
.pipe(
map(res => res),
catchError(this.handleError)
);
}
// error handler
private handleError(error:any, caught:any): any{
sessionStorage.setItem('notFound', 'true');
throw error;
}
}
我的管道:
import { Pipe, PipeTransform } from '@angular/core';
import { TranslationService } from '../services/translation/translation.service';
import { Subscription } from 'rxjs';
@Pipe({ name: 'LanguageTranslate' })
export class TranslateLanguagePipe implements PipeTransform {
private translateReq: Subscription;
public translatedValue: string;
constructor(private translationService: TranslationService){
}
transform(word: string): any {
this.translationService
.translateRequest(word)
.subscribe(result => {
if(localStorage.getItem('language') == 'fr')
this.translatedValue = result.text[0];
else this.translatedValue = word;
return this.translatedValue
});
console.log(this.translatedValue)
}
}
并且在我的 HTML 上非常简单 {{ title |语言翻译 |异步 }}
我的问题是它一直返回一个未定义的。管道不等待订阅完成。
最佳答案
您不必在 LanguageTranslate
内订阅管道。而是只返回一个可观察的字符串(已翻译)。
@Pipe({ name: "LanguageTranslate" })
export class TranslateLanguagePipe implements PipeTransform {
constructor(private translationService: TranslationService) {}
public transform(word: string): Observable<string> {
return this.translationService.translateRequest(word).pipe(
map(response => {
if (localStorage.getItem("language") == "fr") {
return result.text[0];
} else {
return word;
}
})
);
}
}
然后在 HTML 中,您可以使用
async
管道<p>{{ title | LanguageTranslate | async }}</p>
关于javascript - 如何使用在 Angular Pipe 中执行 HTTP 请求的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58704598/