在Angular中,有時候咱們須要從一個文件中讀取數據,如今說明下讀取一個JSON文件的數據的步驟:json
{ "姓名": "李白", "姓別": "男", "年齡": 18 }
constructor(private http: Http) { }
爲了使用這個依賴,要在模塊中引入HttpModule,而且Imports進來:this
import { HttpModule } from '@angular/http';
imports: [
……
HttpModule,
……
],
this.http.get('assets/data.json') .map(data => data.json()) .subscribe(data => { console.log(data); });
一、必定要把data.json放入assets中,否則會報找不到文件的錯誤,緣由是由於Angular的配置限定了資源文件的所在地。咱們能夠打開.angular-cli.json文件,看到了assets這個屬性,能夠發現資源文件中只規定了assets的路徑,因此在其餘文件夾的資源Angular在編譯過程當中會忽略:spa
二、固然,可能能夠在assets中添加其餘路徑,我猜也是能夠的,雖然我沒嘗試過。code