簡體   English   中英

angular2使用http讀取json文件

[英]angular2 read json file using http

嘗試從本地項目中讀取json文件進行一些基本配置。

碼:

myM: any;

constructor(private http: Http) {
     this.http.get('config.json')
        .map((res: Response) => res.json())
        .subscribe(res => {
            this.parseHeaderJSON(res);
        });
}
parseHeaderJSON(res) {
    this.myM = res;
}

HTML:

<li><a href="{{myM.home_header.whatis.link_url}}" class="ripple-effect">{{myM.home_header.whatis.link_name}}</a></li>

但它始終以未定義的身份登錄控制台

如果我放置console.dir(res)而不是賦值,那么它會打印我的對象數據,但不知道為什么它沒有賦給變量!

誰能告訴我我哪里錯了?

更新

json文件內容:

{
  "home_header": 
  {   
  "servicesweoffer":
      {
        "lable_name":"SERVICES WE OFFER",
        "link_url":""        
      },
  "pricing":
      {
        "lable_name":"PRICING",
        "link_url":""
      },      
  "contacutus":
      {
        "lable_name":"CONTACT US",
        "link_url":""
      }
  }
}

console.dir(this.myM)將打印undefined因為

this.http.get('config.json')
    .map((res: Response) => res.json())
    .subscribe(res => this.myM = res);

異步操作。 意味着http.get會在一段時間后返回您一些內容(取決於網絡速度和其他因素),並且您可以在subscribe的http回調內部使用此響應進行操作。

這就是為什么如果將console.dir(res)放在回調中會顯示該值的原因。 因此,當您分配this.myM = res; 您沒有做錯任何事情,只需花費一點時間即可執行此操作。

例:

constructor(private http: Http) {
    this.http.get('config.json')
        .map((res: Response) => res.json())
        .subscribe((res) => {
             //do your operations with the response here
             this.myM = res;
             this.someRandomFunction(res);  
        );
}

someRandomFunction(res){
    console.dir(res);
}


<li><a href="{{myM?.home_header?.whatis?.link_url}}" class="ripple-effect">{{myM?.home_header?.whatis?.link_name}}</a></li>

此范圍不適用於訂閱

myM: any;

constructor(private http: Http) {
    let _self = this;
     this.http.get('config.json')
     .map((res: Response) => res.json())
     .subscribe(
        res => _self.myM = res
     );
        console.dir(this.myM);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM