2016-09-11 62 views
0

我想從遠程服務器獲取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

非常感謝

+0

該問題是由阻塞所有傳出請求的瀏覽器插件引起的。與禁用的東西效果很好。 –

回答

0

這是Angular2我推測。

我認爲你有一個CORS問題。在您的開發工具中檢查您的網絡選項卡。

您無法從其他服務器獲取數據。 (除非其他服務器支持jsonp或返回正確的訪問控制標頭)。這可能適用於本地,因爲您也從本地主機提供您的應用程序。

+0

在這種情況下,raw.githubusercontent.com確實具有這些標頭:Access-Control-Allow-Origin:「*」 –