如何在 Ionic2 框架中解析 Json 数据?

How to parse Json data in Ionic2 framework?

我从 api 到 ajax post call.Here 收到了 json 回复 是我的json 回应

JSON 响应:

{ "s":是的, "m": { "i": 10, "n": "Apple Watch", "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

您必须使用 elvis 运算符,因为最初 insdata 是空对象,而您正试图访问尚不存在的密钥。

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

由于您是从服务器获取信息(通过 this.http.post(...)),因此当 Angular 尝试呈现视图时,响应将不可用。这就是为什么你会收到错误 Cannot read 属性 'm' of undefined,因为 属性 insdata 仍然未定义时间。

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

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

如果你只想打印一个 属性,这种方法是可以的,但如果你需要显示更多的属性,如果你在每个地方都包含 ? 会有点丑你的看法。更好的方法可能是像这样使用 *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 运算符似乎是一个糟糕的选择。