【问题标题】:Get attributes of the first object in angular async pipe获取角度异步管道中第一个对象的属性
【发布时间】:2018-10-10 16:07:04
【问题描述】:

我正在使用 rxjs 和 angular 6,并且我有以下简单的 html 来通过异步管道呈现一堆数据

          <div *ngIf='results | async ; let items '>                                                
            <div *ngFor='let item of items'>
              <div>                    
                {{item.name}} already exists
              </div> 
            </div> 
          </div>

现在,我不想渲染所有这些,只渲染第一个,所以我尝试做类似的事情

          <div *ngIf='results | async ; let items '>                                                
            <div *ngIf='items.length>0'>
              <div>                    
                {{items[0].name}}  already exists
              </div> 
            </div> 
          </div>

items[0] 没有给出错误,items[0].name 有效,但我在控制台中得到了Cannot read property 'name' of undefined

我该如何解决这个问题?

谢谢

【问题讨论】:

  • 请检查添加这个 -> items[0]?.name
  • 如果添加{{ items[0] | json }},您会在模板中看到什么?
  • 你可以使用 observable.pipe(take(1));在您的组件中,然后像在第一个示例中一样继续。

标签: angular asynchronous rxjs


【解决方案1】:
<div *ngIf='results | async ; let items;'>                                                
  <div>{{items[0]?.name}}  already exists</div> 
</div>

【讨论】:

    猜你喜欢
    • 2016-09-05
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 2019-09-03
    • 2018-09-11
    • 1970-01-01
    • 2013-07-18
    相关资源
    最近更新 更多