【问题标题】:angular2 read json file using httpangular2使用http读取json文件
【发布时间】:2016-12-12 06:10:43
【问题描述】:

尝试从我的本地项目中读取 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>

但它总是以 undefined..

身份登录控制台

如果我放置 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":""
      }
  }
}

【问题讨论】:

    标签: javascript json angular


    【解决方案1】:

    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>
    

    【讨论】:

    • 仍然未定义。我也尝试在ngOnInit 中打印myM,但也没有得到它。
    • @JavaCuriousღ ngOnInitconstructor 之后执行很少。如果你想对这个响应做一个操作,你必须在回调内部做。
    • @JavaCuriousღ 您想在哪里读取这些值?给我看一个用例。
    • 我想让所有这些读取的 json 文件和所有使用服务.. 所以我只需调用它的函数 readHeader 所以它会给我它的值.. 我将添加进一步的配置和我的 json 中的错误数据文本,所以一切都会逐渐出现在 json 中。所以为了阅读和json和处理我想要服务的内容..
    • @JavaCuriousღ 然后在http.get 回调中调用服务函数?
    【解决方案2】:

    此范围在订阅中不起作用

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

    【讨论】:

    • 仍然未定义。
    • @anshuVersatile 您可以在函数内部使用 this,因为它是一个 ES6 箭头函数,不绑定 this。
    猜你喜欢
    • 2014-08-07
    • 1970-01-01
    • 2016-06-12
    • 2016-09-17
    • 1970-01-01
    • 2015-01-19
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多