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

标签 javascript angular ionic-framework ionic2

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

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;
  }
}

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

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

错误是

Cannot read property 'vegtable' of undefined

最佳答案

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

你可以做的是用 *ngIf="cart" 放置一个 DOM 元素包含另一个*ngIf .例如:

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

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

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

关于javascript - 无法读取未定义的 angular2 ngif 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41985595/

相关文章:

php - 使用刷新按钮刷新验证码

javascript - 如何仅按文件夹名称导入桶?

angular - 错误 TS2339 : Property 'takeUntil' does not exist on type 'Observable<Foo>' and other rxjs v. 6 个错误

ios - ngx-translate 不适用于 iOS

css - Ionic 4 Slides(带滑动器的 ionic 幻灯片)居中但不是第一个和最后一个

java - 为 cordova (Android) 开发插件时无法找到源 java 类

javascript - 在使用 ASP.Net 或 JavaScript 将图像复制到网站剪贴板方面需要帮助吗?

javascript - Magento:类型错误:N 不是函数

javascript - 我可以让某人使用我网站上的代码在不同的浏览器中打开网站吗

html - Angular 2 : create divs dynamically