最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use a Service that executes HTTP request inside an Angular Pipe - Stack Overflow

programmeradmin0浏览0评论

I'm trying to create an Angular custom pipe that translate a text to other language. All data are dynamic.

Here's my service:

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(`.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;
    }
}

My 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)

    }
}

and on my HTML is very simple {{ title | LanguageTranslate | async }}

My problem is It keeps returning an undefined. The pipe is not waiting for the subscription to finish.

I'm trying to create an Angular custom pipe that translate a text to other language. All data are dynamic.

Here's my service:

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

My 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)

    }
}

and on my HTML is very simple {{ title | LanguageTranslate | async }}

My problem is It keeps returning an undefined. The pipe is not waiting for the subscription to finish.

Share Improve this question edited Nov 5, 2019 at 5:00 Sherwin Ablaña Dapito asked Nov 5, 2019 at 4:38 Sherwin Ablaña DapitoSherwin Ablaña Dapito 9681 gold badge17 silver badges34 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You don't have to subscribe inside the LanguageTranslate pipe. Instead just return an observable of string(translated).

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

and then in HTML, you can use async pipe

<p>{{ title | LanguageTranslate | async }}</p>
发布评论

评论列表(0)

  1. 暂无评论