我正在使用angular2创建应用程序,我需要从雅虎天气获得天气.我尝试使用http get方法,但它给了我一个错误.
import {Component,OnInit,} from "angular2/core";
import {Http} from "angular2/http";
import 'rxjs/add/operator/map';
@Component({
templateUrl:'app/contact/contact.html',
})
export class ContactComponent{
constructor (private http: Http) {}
public url:string= "http://weather.yahooapis.com/forecastjson?w=2295424";
ngOnInit(url:string) {
return this.http.get(url).map(res => {
return res.json();
}).subscribe((response) => { console.log(response) });
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是
EXCEPTION:SyntaxError:JSON.parse:JSON数据第1行第1列的意外字符
谁能帮我这个?.
小智 6
您需要将Accept标头附加到get请求,以便Firefox呈现返回的json.我在搜索了很多之后发现了这个并且遇到了这个https://brockallen.com/2012/04/27/change-firefoxs-default-accept-header-to-prefer-json-over-xml/这导致了我的失望添加标题的路径
ngOnInit() {
let headers = new Headers();
headers.append('Accept', 'q=0.8;application/json;q=0.9');
return this.http.get(this.url, { headers: headers } ).map(res => {
return res.json();
}).subscribe((response) => { console.log(response) });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3284 次 |
| 最近记录: |