Jcvf90
Jcvf90

Reputation: 21

In Angular v4, is it possible to use the Google translator API to send it text, and receive a translation?

And if it is, how? I'm learning webapp stuff. And I'm trying to make a translator. I already setup my html to receive an input string. But now I don't know how to proceed. I'm looking through the google translate api documentation here and I see some stuff for Node but I'm not sure if that would work for Angular. What am I supposed to import? A friend mentioned ajax requests, how would I go about that?

Any help or pointing in a good direction would be very helpful. Thank you!

Upvotes: 0

Views: 5837

Answers (2)

Sai Pandu
Sai Pandu

Reputation: 21

 component.TS
......................................

ngAfterViewInit() {
        var v = document.createElement("script");
        v.type = "text/javascript";
        v.innerHTML = "function googleTranslateElementInit() { new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google_translate_element'); } ";
        this.elementRef.nativeElement.appendChild(v);
        var s = document.createElement("script");
        s.type = "text/javascript";
        s.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
        this.elementRef.nativeElement.appendChild(s);
    }
<div id="google_translate_element"></div>

Upvotes: 2

scotty3
scotty3

Reputation: 153

This will get you closer, using the Angular HttpClient to send a Get with parameters but you'll have to do additional work to load your API key and handle an authorization response. Please do the Angular tutorial as mentioned first. https://angular.io/tutorial

https://stackblitz.com/edit/angular-httpclient-ex5

import { Component } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

@Component({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: [ './app.component.css' ]
})

export class AppComponent  {
apiKey = ''
url = 'https://translation.googleapis.com/language/translate';
result: any;
q: any;

constructor(private http: HttpClient) {}  

translate(): void {
 let params = new HttpParams();
 params = params.append('q', this.q);
 params = params.append('target', 'es');
 params = params.append('key ', this.apiKey);

 this.http.get(this.url, {params: params})
   .subscribe(response => this.result = response);

}

Upvotes: 0

Related Questions