2016-09-11 65 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:“*” –