如何使用Google翻译节点库angular 4

How to use Google translate node library in angular 4

我想在我的 angular 4 应用程序中使用 google 翻译库。我没有看到任何文件。所以我正在休息 api。休息 API 我得到低于响应。当我在邮递员中使用相同的 url 时,它工作正常。

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}`, {});
  }
}

回应

{
  "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"
  }

任何人都可以帮助我我做错了什么以及我如何在 angular 4

中使用普通的 nodejs 库

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

问题在于 Authorization header 随请求一起发送到 Google Translate API

Google Translate API 将在请求 header 中查找 Authorization header 并从中提取值以用作 API Key。拥有 Authorization header、Google Translate API 将忽略请求 URL 中的 key queryParameter。

您需要做一些逻辑来 NOTPOST 上的 Authorization 附加到 API 或使用 API Key 作为 Authorization header 而不是 User's Token