angular2使用http读取json文件 [英] angular2 read json file using http

查看:429
本文介绍了angular2使用http读取json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从本地项目中读取json文件以进行一些基本配置.

trying to read json file from my local project for some basic config.

代码:

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>

,但它始终以 undefined ..

如果我放置console.dir(res)而不是赋值,那么它将打印我的对象数据,但不知道为什么它没有赋给变量!!!

if I place console.dir(res) instead of value assign then it prints my object data but don't know why it does not assign to variable !!!

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

can anyone tell me where am I wrong ?

更新

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回调中使用此响应进行操作.

is an async operation. Meaning http.get will return you something after a time (depending on network speed and other stuff) and you can do something with this response inside the http callback which is inside subscribe.

这就是为什么如果将console.dir(res)放置在回调中会显示该值的原因.因此,当您分配this.myM = res;时,您没有做错任何事情,只需花费一点时间即可执行此操作.

That is why if you place console.dir(res) inside the callback it prints the value. So when you are assigning this.myM = res; you are not doing anything wrong, it just takes a little time to do this operation.

示例:

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>

这篇关于angular2使用http读取json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆