Use Google Translation API in your Angular App

Ivy Walobwa
4 min readMar 27, 2020

Hallo tolle Entwickler 😎, in this post we will be using the cloud translation service in an angular application. (translation documentation)

Prerequisites

Angular CLI already installed

Node.js Installed

Angular project already set up

What are our objectives?

  • Display data from a json file to user
  • Give user a chance to select language from a drop down
  • Translate to selected language

Let’s dive in.

Provided the starter code here. You can fork and code along. The starter code displays data from a json file (first objective).

Set up project for the Cloud Translation Service

To set up your project;

  • Visit the Cloud translation documentation
  • Click on set up project.
  • Then click on the ‘Cloud Console’ link provided before step 2.
  • Then go to API overview and select credentials to obtain your API key.

Make Requests to the translation service

We will be making POST http requests to the endpoint, https://translation.googleapis.com/language/translate/v2 .

In our application;

  1. Generate a service that would be used to make requests to the endpoint.

ng g s services/googletranslate

Inside the googletranslate.service.ts file, add the following code inside the class;

url = ‘https://translation.googleapis.com/language/translate/v2?key=';key = ‘’;constructor(private http: HttpClient) { }translate(obj: GoogleObj) {return this.http.post(this.url + this.key, obj);}

The value of the key property should be the API key which we obtained from our console.

The translate method takes in one parameter of type GoogleObj. This is an object containing our query parameters. There are two required query parameters; the input text (q) and the language to use for translating the input text (target). The method makes a post request to our url concatenated with our API key and takes in the query parameters given. It then returns the response.

Probably wondering where GoogleObj comes from…

In my starter code, I generated an interface (solution.ts) inside the models folder. Add the GoogleObj interface to this file;

export interface GoogleObj {q: string[];target: string;}

2. Update our app.component.html and app.component.ts file

Add a button to the Html file

<button id=”translatebtn” (click)=”send()”>Translate</button>

In our ts file, update code as shown;

...
import { ..., GoogleObj } from ‘./models/solution’;
import { GoogletranslateService } from ‘./services/googletranslate.service’;...export class AppComponent implements OnInit {
...
private translateBtn: any;constructor(..., private google: GoogletranslateService) {}ngOnInit() {...this.translateBtn = document.getElementById(‘translatebtn’);}send() {const googleObj: GoogleObj = {q: ‘hello’,target: ‘es’};this.translateBtn.disabled = true;this.google.translate(googleObj).subscribe((res: any) => {
this.translateBtn.disabled = false;
console.log(res.data.translations[0].translatedText)},err => {console.log(err);});}}

Click on the button and check your console. If the text ‘Hola’ is printed , you successfully managed to use the translation service in your app!!🎉

So what exactly is going on????

In our ts file, we;

  • Created an instance of the GoogleTranslateService
  • created a send() method. In our method, we have googleObj variable which is an object that contains the query parameters,(our input string is ‘hello’, and the language to translate to is Spanish ‘es’). We also subscribe to the translate method in our GoogleTranslateService when the button is clicked, passing googleObj as an argument and print out the response. In this case, ‘Hola’ is printed.

But we want the user to select their own language. We’ll modify the app.component.ts and app.component.html files.

Here is a gist containing the final update.

In our html file, we created a drop down list of languages (used Reactive Forms).

Let’s go through our updated code in the ts file.

send() {const googleObj: GoogleObj = {q: [this.data.title, this.data.description, this.data.detail],target: this.lang.value};this.translateBtn.disabled = true;this.google.translate(googleObj).subscribe((res: any) => {this.translateBtn.disabled = false;this.data = {title: res.data.translations[0].translatedText,description: res.data.translations[1].translatedText,detail: res.data.translations[2].translatedText};console.log(this.data);},err => {console.log(err);});}

The ‘q’ query parameter is an array of strings this time, the title, detail and description of our html. The ‘target’ is the value of the form control ‘lang’, whose default value is ‘en’ (English)

lang = new FormControl(‘en’);

The response this time is not printed to the console, rather it is stored in the data property, which displays on browser. To understand the response try printing it out to the console ie: console.log(res.data) .

This is my final application.

Thank you for your time. Stay safe and happy coding 💖.

--

--