2017-10-10 35 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