错误TypeError:无法读取null的属性“ 0”角度7

时间:2018-12-31 09:56:36

标签: javascript json angular typescript firebase

我正在尝试像这样在component.html中访问Observable:

{{ (pins | async)[0]?.state }}

我不知道是否可以通过这种方式完成操作,但是我想访问html 中的Observable列表的单个部分,而不用* ngFor 循环。 (我正在使用Firebase。) 这是component.ts:

pins: Observable<any[]>;

this.pins = this.db.list('pins').snapshotChanges().pipe(
  map(changes => 
    changes.map(c => ({ $key: c.payload.key, ...c.payload.val() }))
  )
);

这是引脚的json数据:

[
  {
    "$key": "0",
    "pin": 5,
    "state": true
  },
  {
    "$key": "1",
    "pin": 4,
    "state": false
  },
  {
    "$key": "2",
    "pin": 0,
    "state": true
  },
  {
    "$key": "3",
    "pin": 2,
    "state": false
  },
  {
    "$key": "4",
    "pin": 14,
    "state": true
  },
  {
    "$key": "5",
    "pin": 12,
    "state": true
  },
  {
    "$key": "6",
    "pin": 13,
    "state": true
  },
  {
    "$key": "7",
    "pin": 15,
    "state": true
  }
]

它适用于第一项,但其他项不起作用,并且显示此错误:

ERROR TypeError: Cannot read property '0' of null
    at Object.eval [as updateRenderer] (HomeComponent.html:88)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:22503)
    at checkAndUpdateView (core.js:21878)
    at callViewAction (core.js:22114)
    at execComponentViewsAction (core.js:22056)
    at checkAndUpdateView (core.js:21879)
    at callViewAction (core.js:22114)
    at execEmbeddedViewsAction (core.js:22077)
    at checkAndUpdateView (core.js:21874)
    at callViewAction (core.js:22114)

感谢帮助!

2 个答案:

答案 0 :(得分:0)

尝试首先检查变量的长度,然后使用索引位置从列表中获取指定的项:

您的HTML喜欢:

<ul *ngFor="let pin of pins;let i=index">
    <li>{{ pin.state }} <button mat-button (click)="update(i,pin)">Update Status</button></li>
</ul>
<span *ngIf="pins">
   {{ pins[0].state }} and {{pins.length}}
</span>

在TS中:

import { Component } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  pins: any;

  constructor(private db: AngularFireDatabase) { }

  ngOnInit() {
    this.db.list('pins').valueChanges().subscribe(value => {
      this.pins = value;
    });
  }
  update(i,pin)
  {
   this.db.object('/pins/' + i).update({ pin: pin.pin, state: !pin.state });
  }
}

WORKING EXAMPLE

答案 1 :(得分:0)

component.ts

export class AppComponent {
      pins: Observable<any[]>;
      pinsList = [];

      constructor(...) { }

      ngOnInit() {
       ...
       pins..subscribe(pins => this.pinsList = pins);
      }

    }

component.html

{{ pins[0].state }}

或使用:

<ng-container *ngFor="let pin of pins | async; let i = index;">
 <div  *ngIf="i === 0">{{ pin.state }}</div>
</ng-container>