我想从远程服务器获取JSON文件。我写了下面模块:Angular2跨域http获取
import { Component } from '@angular/core';
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import './rxjs-operators';
@Component({
selector: 'map',
templateUrl: 'map/map.component.html'
})
@Injectable()
export class MapComponent{
private properties;
constructor(private http: Http){
this.properties = null;
}
ngOnInit(){
this.getPropertiesInTheArea();
}
getPropertiesInTheArea(){
let url = "https://raw.githubusercontent.com/sdeering/50-jquery-function-demos/cd89f8592b96d0a79c10aa64fa43c1bf01312643/data/data.json";
this.http.get(url)
.map(response => response.json())
.subscribe(
data => this.properties = data,
err => console.error(err),
() => console.log("Properties fetched\n\n" + JSON.stringify(this.properties))
);
}
}
该模块可以完美地获取本地JSON文件:
let url = "http://localhost:3000/map/data.json";
但对远程资源(在raw.githubusercontent.com例如)我在控制台中:
“例外:[异常... ”“ nsresult: ”0x805e0006()“ 位置: ”JS帧:: http://localhost:3000/node_modules/zone.js/dist/zone.js :: scheduleTask ::线1241“ 的数据:无]”
未处理的承诺拒绝:异常{message:“”,结果为:2153644038,name:“”,filename:“http://localhost:3000/node_modules/ ...”,lineNumber:1241,columnNumber:0,data:null,stack:“scheduleTask @http://localhost:3000/ ...” ;区域:;任务:Promise.then;值:Exception {message:“”,result:2153644038,name:“”,filename:“http://localhost:3000/node_modules/ ...”,lineNumber:1241,columnNumber:0,data:null,stack:“scheduleTask @http://localhost:3000/ ...”} undefined
非常感谢
该问题是由阻塞所有传出请求的浏览器插件引起的。与禁用的东西效果很好。 –