【问题标题】:How to parse Json data in Ionic2 framework?如何在 Ionic2 框架中解析 Json 数据?
【发布时间】:2017-03-01 23:21:44
【问题描述】:

我通过 ajax post call 收到了来自 api 的 json 响应。这是我的 json 响应

JSON 响应:

{ “s”:是的, “米”: { “我”:10, "n": "苹果手表", “p”:“14000” }}

实际上,在我的打字稿代码中,我发出了显示 JSON 响应的警报。它运作良好。 当我尝试对 HTML 元素使用响应值时。失败了。

TypeScript

let headers = new Headers({ 'Content-Type': 'application/json'});

    this.value = { 'uid': 10 };

    let body = JSON.stringify(this.value);

    this.http.post(url, body, headers)
        .map(res => res.json())
            .subscribe(
              data => {
               alert(JSON.stringify(data));//Alert displays the response successfully 
               this.insdata=data;     
             },
            err => {
              console.log("Oops!");                
            }
   );

HTML

<h2>{{insdata.m.n}}</h2> //I cannot get the value here.

错误

Runtime Error Error in ./HomePage class HomePage - caused by: Cannot read property 'm' of undefined

【问题讨论】:

    标签: angular ionic2 hybrid-mobile-app


    【解决方案1】:

    您必须使用 elvis 运算符,因为最初 insdata 是空对象,并且您正在尝试访问尚不存在的键。

    <h2>{{insdata?.m?.n}}</h2>
    

    【讨论】:

    • Jankovic.. 感谢您的回复。如果我使用 {{insdata.s}} 它可以通过在

      中打印“true”来正常工作。但是如果我使用 {{insdata.m.n}} 它没有打印值。

    • 这是因为 insdata 最初是一个已定义的对象,而 'm' 最初是未定义的。因此,当您尝试获取“m”中的“n”(未定义)时,它会引发错误。这就是为什么你需要使用 elvis 运算符 (?)
    【解决方案2】:

    由于您是从服务器获取信息(通过this.http.post(...)),因此当 Angular 尝试渲染视图时响应将不可用。这就是为什么您会收到错误无法读取未定义的属性“m”,因为到那时属性insdata 仍然未定义。

    就像@Igor Janković 所说,避免该异常的一种方法是使用 elvis 运算符 ? 让 Angular 知道该属性(或子属性)可能为空。这样,如果 Angular 发现该属性为 null 或未定义,它就不会尝试访问其子属性:

    &lt;h2&gt;{{insdata?.m?.n}}&lt;/h2&gt;

    如果您只想打印单个属性,这种方法是可以的,但如果您需要显示更多属性,如果您在视图中的任何位置都包含?,那会有点难看。更好的方法可能是像这样使用*ngIf

    <!-- Don't render the entire section if insdata is null -->
    <div *ngIf="insdata" class="section">
    
        <!-- 
            Here you can print all the first level properties like
            insdata.s because insdata won't be null
        -->
    
        <p>{{ insdata.s }}</p>
    
        <div *ngIf="insdata.m" class="sub-section">
    
            <!-- 
                Here you can print all the properties from m
                because insdata.m won't be null
            -->
    
            <h2>{{insdata.m.n}}</h2>
    
        </div>
    
    </div>
    

    再次请注意,如果您只想打印h2 元素,您可以使用elvis 运算符,仅此而已。我只是想告诉你,有时我们需要在视图中显示复杂的对象(有很多嵌套的子属性),而 elvis 运算符在这些情况下似乎是一个糟糕的选择。

    【讨论】:

      猜你喜欢
      • 2021-10-28
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 2017-03-19
      • 1970-01-01
      • 2021-08-29
      相关资源
      最近更新 更多