Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何在Ionic2框架中解析Json数据?_Angular_Ionic2_Hybrid Mobile App - Fatal编程技术网

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

Angular 如何在Ionic2框架中解析Json数据?,angular,ionic2,hybrid-mobile-app,Angular,Ionic2,Hybrid Mobile App,我通过ajax post调用从api收到了一个json响应 JSON响应: { “s”:是的, “m”: { “i”:10, “n”:“苹果手表”, “p”:“14000” }} 实际上,在我的typescript代码中,我发出了一个警报以显示JSON响应。它工作得很好。 当我尝试对HTML元素使用响应值时。这是不成功的 类型脚本: let headers = new Headers({ 'Content-Type': 'application/json'}); this.value

我通过ajax post调用从api收到了一个json响应

JSON响应:

{ “s”:是的, “m”: { “i”:10, “n”:“苹果手表”, “p”:“14000” }}

实际上,在我的typescript代码中,我发出了一个警报以显示JSON响应。它工作得很好。 当我尝试对HTML元素使用响应值时。这是不成功的

类型脚本

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.
{{insdata.m.n}}//我无法在此处获取值。
错误

运行时错误

./HomePage类HomePage中的错误-原因:无法读取未定义的属性“m”

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

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

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

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

{{insdata?.m?.n}

如果您只想打印单个属性,这种方法是可以的,但是如果您需要显示更多属性,那么如果您在视图中的任何地方都包含
,则会有点难看。更好的方法可能是使用
*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>

{{insdata.s}

{{insdata.m.n}

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

Jankovic。。谢谢你的回复。如果我使用{{insdata.s},它可以通过在内部打印“true”很好地工作。但是如果我使用{insdata.m.n},它不会打印值。这是因为insdata最初是一个已定义的对象,而“m”最初是未定义的。因此,当您尝试获取'm'中的'n'(未定义)时,它会抛出一个错误。这就是为什么需要使用elvis运算符(?)