繁体   English   中英

如何使用在 Angular Pipe 中执行 HTTP 请求的服务

[英]How to use a Service that executes HTTP request inside an Angular Pipe

我正在尝试创建一个 Angular 自定义 pipe 将文本翻译成其他语言。 所有数据都是动态的。

这是我的服务:

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;
    }
}

我的 Pipe:

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 | 语言翻译 | 异步}}

我的问题是它一直返回一个未定义的。 pipe 不等待订阅完成。

您不必在LanguageTranslate pipe 中订阅。 而是只返回一个可观察的字符串(已翻译)。

@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 pipe

<p>{{ title | LanguageTranslate | async }}</p>

您是否尝试过使用异步 pipe 或去抖动超时来延迟订阅返回?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM