无法读取未定义 angular2 ngif 的属性

Cannot read property of undefined angular2 ngif(无法读取未定义 angular2 ngif 的属性)
本文介绍了无法读取未定义 angular2 ngif 的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我现在可以在视图中获取对象,但是我无法运行 if 语句.根据之前的回答,这就是我引入对象的方式.

I am now able to get the object in the view however I cannot run an if statement. Per previous answer this is how I am bringing in the object.

public getPosts$(category, limit) {
  return this.cartService.getPosts(category, limit).map(response => {
    return response && response.data && response.data.children;
  };
}

ngOnInit() {
  this.getPosts$(this.category, this.limit).subscribe(cart => {
    this.cart = cart;
  }
}

我正在尝试运行,但无法获得属性蔬菜.

I am trying to run but get cannot get property vegetable.

<h2 *ngIf="cart">{{cart.vegetable}}</h2>
<h2 *ngIf="cart.vegetable == 'carrot' ">{{cart.vegetable}}</h2>

错误是

无法读取未定义的属性vegtable"

Cannot read property 'vegtable' of undefined

推荐答案

cart 对象为空,直到服务 getPosts$ 返回(回调).因此,代码 *ngIf="cart.vegetable ... 等于 *ngIf="null.vegetable ... 直到发生这种情况.这就是正在发生的事情.

The cart object is null until the service getPosts$ returns (callback). Therefore, the code *ngIf="cart.vegetable ... is equal to *ngIf="null.vegetable ... until that happens. That is what is happening.

您可以做的是放置一个带有 *ngIf="cart" 的 DOM 元素,其中包含另一个 *ngIf.例如:

What you could do is put a DOM element with *ngIf="cart" containing the other *ngIf. For example:

<div *ngIf="cart">
    <h2 *ngIf="cart.vegetable == 'carrot' ">{{cart.vegetable}}</h2>
</div>

*正如在下一个答案中所说,一个很好的选择(和良好的做法)如下:

* As it is said in the next answer, a good alternative (and good practice) is the following:

<h2 *ngIf="cart?.vegetable == 'carrot' ">{{cart.vegetable}}</h2>

这篇关于无法读取未定义 angular2 ngif 的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I can get a text of all the cells of the table using testcafe(如何使用 testcafe 获取表格中所有单元格的文本)
node_modules is not recognized as an internal or external command(node_modules 未被识别为内部或外部命令)
How can I create conditional test cases using Protractor?(如何使用 Protractor 创建条件测试用例?)
PhantomJS and clicking a form button(PhantomJS 并单击表单按钮)
Clicking #39;OK#39; on alert or confirm dialog through jquery/javascript?(在警报上单击“确定或通过 jquery/javascript 确认对话框?)
QunitJS-Tests don#39;t start: PhantomJS timed out, possibly due to a missing QUnit start() call(QunitJS-Tests 不启动:PhantomJS 超时,可能是由于缺少 QUnit start() 调用)