angular2:错误:TypeError:无法读取未定义的属性“ ...”

编程入门 行业动态 更新时间:2024-10-26 10:38:44
本文介绍了angular2:错误:TypeError:无法读取未定义的属性“ ...”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已附上我的angular2代码段的小栓。我想从JSON打印一个字段,但由于最初我的Object为null,并且无法通过Promise进行填充,因此无法打印。

I have attached the plunker of my angular2 code piece. I want to print a field from my JSON but unable to print that as initially my Object is null and it is being populated via a Promise.

这是我的组件文件

import {Component, NgModule, OnInit} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' class MyData { xyz : MySubData; } class MySubData { name : string; } @Component({ selector: 'my-app', template: ` <div> <h2>Hello {{name}}</h2> {{abc.xyz.name}} </div> `, }) export class App implements OnInit { abc : MyData = null; constructor() { this.name = 'Angular2' } ngOnInit() { setTimeout(() => { this.abc = new MyData(); this.abc.xyz = new MySubData(); this.abc.xyz.name = "Binita"; }, 2000); } } @NgModule({ imports: [ BrowserModule ], declarations: [ App ], bootstrap: [ App ] }) export class AppModule {}

当我删除行 {{abc.xyz.name}} 在我的模板中运行正常。

When I am removing the line {{abc.xyz.name}} from my template it is running fine.

我已经使用了set在代码中超时,因为我正在从Promise中获取数据(即异步调用)。

I have use set time out in my code because I am getting my data from Promise (i.e asynchronous call).

最初我可以理解为 abc 为 null ,我的代码无法找到abc.xyz.name。但是我不想检查任何条件。因为我在JSON中有几个属性,所以如果条件满足,则不可能为每个属性写。

I can understand initially as abc is null, my code is unable to find abc.xyz.name. But I don't want to put any if condition to check. Because I have several property inside a JSON and it is not possible for each property to write if condition.

angularjs 1的早期版本,如果abc为null,那么它将自动替换它与空白字符串。我想在angular2中做同样的事情。请提出建议。

Earlier in angularjs 1 if abc is null then it would automatically replace it with blank string. I want to do the same thing in angular2. Please suggest.

下面是the车手

plnkr.co/edit/u1NqNF0penz7OS55QmoU?p=preview

推荐答案

这是因为在模板渲染时未定义 abc 。您可以使用安全的导航运算符(?)来保护模板,直到HTTP调用完成:

That's because abc is undefined at the moment of the template rendering. You can use safe navigation operator (?) to "protect" template until HTTP call is completed:

{{abc?.xyz?.name}}

您可以阅读有关安全导航操作员的详细信息,请此处。

You can read more about safe navigation operator here.

更新:

不能在数组中使用安全的导航运算符,您必须利用 NgIf 指令来克服此问题:

Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf directive to overcome this problem:

<div *ngIf="arr && arr.length > 0"> {{arr[0].name}} </div>

了解有关 NgIf 指令此处。

更多推荐

angular2:错误:TypeError:无法读取未定义的属性“ ...”

本文发布于:2023-11-22 23:19:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619307.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   错误   未定义   TypeError

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!