user_27
user_27

Reputation: 231

How to use Google translate node library in angular 4

I want to use google translate library in my angular 4 app. I didn't saw any documentation. So i am working on rest api. With rest API i am getting below response. when i use same url in postman it is working fine.

app.service.ts

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

@Injectable()
export class HttpService {

    userData : any;

    constructor(public http: HttpClient) {}

    /*  First parameter is url.
        second is object of request params.
        Don't pass 2nd paramater if not required.
    */
    get<T>(url, requestParams?:Object) {
        let options = {};
        options = this.getOptions(requestParams);
        return this.http.get<T>(url,options);
    }

    /*  First parameter is url.
        second is request body. Pass atleast null if no body for your request.
        Third is request parameters.
        Don't pass 3rd paramater if not required.
    */
    post<T>(url, postBody: any, requsetParams?: Object) {
        let options = {};
        options = this.getOptions(requsetParams);
        return this.http.post<T>(url,postBody, options);
    }

    /*  First parameter is url.
        second is object of request params.
        Don't pass 2nd paramater if not required.
    */
    delete(url, requestParams?: Object) {
        let options = {};
        options = this.getOptions(requestParams);
        return this.http.delete(url, options);
    }

    /*  First parameter is url.
        second is request body. Pass atleast null if no body for your request.
        Third is request parameters.
        Don't pass 3rd paramater if not required.
    */
    put(url, putData, requsetParams?: Object) {
        let options = this.getOptions(requsetParams);
        return this.http.put(url, putData, options);
    }

    getOptions(requestParams?: Object) {

        let options = {};

        this.userData = JSON.parse(localStorage.getItem("currentUser"));
        if(this.userData !== null) {
            let headers = new HttpHeaders({
                'authorization': 'Bearer ' + this.userData.token
            })
            options['headers'] = headers;
        }

        if(requestParams !== undefined) {
            let httpParams = new HttpParams();
            Object.keys(requestParams).forEach(function (key) {
                httpParams = httpParams.append(key, requestParams[key]);
            });

            options['params'] = httpParams;
        }

        return options;
    }

}

myservice.ts

import { Injectable } from '@angular/core';
import { HttpService } from '../http.service';
import { TranslateResponse } from './model/translate-response';
import { Observable } from 'rxjs/Observable';
import { DetectLanguageResponse } from './model/detect-language-response';

const googleTranlateApiURL: string = 'https://translation.googleapis.com/language/translate/v2';
const googleTranlateApiKey: string = '';
const googleTranlateApiFormat: string = 'text';


@Injectable()
export class GoogleTranslateService {



  constructor(private httpService: HttpService) { }

  translate(q: string, target: string, source: string): Observable<TranslateResponse> {
    return this.httpService.post<TranslateResponse>(`${googleTranlateApiURL}?q=${q}&target=${target}&source=${source}&key=${googleTranlateApiKey}`, {});
  }

  detect(q: string): Observable<DetectLanguageResponse> {
    return this.httpService.post<DetectLanguageResponse>(`${googleTranlateApiURL}/detect?q=${q}&key=${googleTranlateApiKey}`, {});
  }
}

response

{
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "errors": [
      {
        "message": "Request had invalid authentication credentials.",
        "reason": "authError"
      }
    ],
    "status": "UNAUTHENTICATED"
  }

Any one can help me what wrong i am doing and how i can use plain nodejs library in angular 4

https://cloud.google.com/translate/docs/reference/libraries

Upvotes: 1

Views: 1099

Answers (1)

Chau Tran
Chau Tran

Reputation: 5088

The problem lies in the Authorization headers being sent along with the request to Google Translate API.

Google Translate API will look for an Authorization header in the request headers and will extract the value from it to use as the API Key. Having the Authorization header, Google Translate API will ignore the key queryParameter in the request URL.

Either you need to do some logic to NOT appending Authorization on POST to the API or use the API Key as the Authorization header instead of the User's Token.

Upvotes: 2

Related Questions