我想從遠程服務器獲取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
非常感謝
該問題是由阻塞所有傳出請求的瀏覽器插件引起的。與禁用的東西效果很好。 –