2017-07-03 35 views
0

我是Angular 2.0的新手,我嘗試使用@angular\cli來構建示例應用程序。錯誤:0:0造成的:狀態響應:0爲URL:null Angular 2.0問題

因此,我使用ng serve --open來爲localhost:4200中的應用程序提供服務。

現在,我有一個名爲example.service.ts服務,代碼如下:

import { Injectable } from '@angular/core'; 
import { Http,Response } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Injectable() //Decorator 

export class ExampleService { 
    private _url : string = "file:///Users/chiranjib/Documents/Angular%202%20Tutorial/ninja-app/apidata/employeedata.json"; 
    constructor(private _http : Http){} 
    getEmployees(){ 
     return this._http.get(this._url) 
      .map((response : Response) => response.json()); 
    } 
} 

文件employeedata.json駐留在apidata文件夾內的地方。

在我component我做的:

this._exampleService.getEmployees().subscribe((resEmployeeData) => this.employees = resEmployeeData); 

但它顯示了錯誤:

enter image description here

即使在火狐錯誤仍然存​​在。

如果這樣做,

private _url : string = "apidata/employeedata.json"; 

錯誤顯示:

enter image description here

如何解決錯誤,讓我的應用程序的工作?

+0

第一個圖像是一個cors問題,通常導致應用程序在兩個不同的域中,第二個是未找到的,這意味着無法找到資源。 – TGarrett

+0

請包括錯誤作爲文字,而不是圖像。 –

+0

你在應用程序文件夾中有json文件嗎?什麼是應用程序結構 – Aravind

回答

2

該錯誤消息

的XMLHttpRequest不能加載file://...。交叉源請求僅支持協議方案http,data,chrome,chrome-extension,https。

表示出於安全原因,瀏覽器拒絕加載來自file:// url的JSON。這是有道理的,因爲如果網站被允許讀取用戶硬盤上的文件,這將是一個隱私的噩夢。

具體而言,對不同origin的網址的任何請求都需要請求的網址的special permission,並且不會爲file://網址提供此類權限。

爲了解決這個問題,你需要通過HTTP提供JSON(理想情況下來自同一個主機和端口,因此它在同一個原點上)。在角度CLI中完成此操作的最簡單方法是將其放入src/assets文件夾中,並從/assets/employeedata.json加載它。

+0

感謝這個美麗的解釋和解決方案。 – StrugglingCoder

相關問題