1

我想在我的 Angular 4 应用程序中使用谷歌翻译库。我没有看到任何文档。所以我正在研究rest api。使用其余 API,我得到了以下响应。当我在邮递员中使用相同的网址时,它工作正常。

应用服务.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;
    }

}

我的服务.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

4

1 回答 1

2

问题在于Authorization标头与请求一起发送到Google Translate API.

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

您需要执行一些逻辑来NOT附加AuthorizationPOSTAPI,API Key或者Authorization使用User's Token.

于 2018-04-17T19:00:57.113 回答