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.
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.
Angular provides a client HTTP API for Angular applications, the HttpClient service class in @angular/common/http .
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With