如何在角度4

时间:2018-04-17 17:09:33

标签: node.js angular google-translate google-translation-api

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

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

任何人都可以帮助我,我正在做什么错,以及我如何在角4中使用普通的nodejs库

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

1 个答案:

答案 0 :(得分:1)

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

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

您需要做一些逻辑以NOTAuthorization POST附加到API上,或使用API Key作为Authorization标题,而不是User's Token