我正在尝试像这样访问 component.html 中的 Observable:
{{ (pins | async)[0]?.state }}
我不知道是否可以通过这种方式完成,但我想访问 html 中 Observable 列表的单个部分而不使用 *ngFor 循环。 (我正在使用 firebase。) 这是组件.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)
感谢您的帮助!
最佳答案
尝试先检查变量的长度,然后使用索引位置从列表中获取指定的项目:
所以你的 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 });
}
}
关于javascript - 错误类型错误 : Cannot read property '0' of null | Angular 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53986060/