2017-10-10 34 views
0

我試圖通過http在Angular 4中獲取服務來連接到google API,但是我無法訪問。代碼如下所示:在Angular 4中使用Google API

const requestHeaders = new Headers(); 
requestHeaders.append('Content-Type', 'application/x-www-form-urlencoded'); 

const options = new RequestOptions({ headers: requestHeaders }); 
const myURL = 'https://kgsearch.googleapis.com/v1/entities:' + 
    'search?query=taylor+swift&key=MYKEY&limit=1&indent=True'; 
return this.http.get(myURL, options) 
.map((res: Response) => res.json()) 
.subscribe(
    data => console.log(data), 
    err => console.log(err), 
    () => console.log('output') 
); 

回答

0

上面的代碼中的所有內容看起來都不錯,除了兩件事情需要注意。

  1. RequestOptions在這裏不是強制性的。所以請避免使用它。直到你需要它,http請求才會觸發而不用RequestOptions

  2. Content-type,它的數值應是適當的按 的數據類型由谷歌-API返回結果的

下面是我的代碼示例工作正常。

  • MyService.ts文件

    import { Observable } from 'rxjs/Rx'; let httpRequestHeaders = new Headers(); httpRequestHeaders.append('Content-Type', 'application/json; charset=UTF-8'); GetMyData(): Observable<any> { return this.http.get('myURL ', httpRequestHeaders); }

  • some.Component.ts文件

    SomeMethod() { this.MyService.GetMyData() .subscribe((resp) => { console.log(resp); }, err => { //this.logger.LogError('Erro while fetching data'); }); }

+0

不能使用httpRequestHeaders HTTP GET裏面,你應該使用:const options =新的RequestOptions({headers:requestHeaders});並在代碼中使用選項 - 。 this.http.get(myURL,options) – Eni