Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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.

like image 723
Sherwin Ablaña Dapito Avatar asked Nov 05 '19 04:11

Sherwin Ablaña Dapito


People also ask

Can I use pipe in service Angular?

You don't have to duplicate your code if you want to also use a pipe's functionality in a component class. All you have to do really is inject the pipe like a service, and then call its transform method. The following works for any Angular 2+ app.

What is the name of the class Angular uses to support HTTP in a component service?

Angular provides a client HTTP API for Angular applications, the HttpClient service class in @angular/common/http .

What is HTTP service in Angular?

The $http service is a core AngularJS service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP. For unit testing applications that use $http service, see $httpBackend mock.

How are pipes executed in Angular?

You use data binding with a pipe to display values and respond to user actions. If the data is a primitive input value, such as String or Number , or an object reference as input, such as Date or Array , Angular executes the pipe whenever it detects a change for the input value or reference.


1 Answers

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>
like image 123
Prabh Avatar answered Oct 07 '22 19:10

Prabh