Angular2使用HTTP读取JSON文件



尝试从我的本地项目中读取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)而不是分配值,则它会打印我的对象数据,但不知道为什么它不分配给变量!

谁能告诉我我在哪里错了?

update

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);

async 操作。这意味着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);
}

最新更新