我试图更新我的ionic2应用程序中的firebase中的数据,我得到这个错误:cannot read property '$key' of undefined
.TS
onValidate(info): void{
//console.log(info.$key);
this.infos.update(info.$key,{
FirstName : info.FirstName,
LastName : info.LastName
})
}
html的
<button
ion-button
type="submit"
block
[disabled]="!f.valid"
(click)="onValidate(info)">Valider</button>
在我的HTML中我有一个* ngFor =“让信息的信息|异步”...
谢谢您的帮助
我假设你在这里使用firebase。你永远不会从角度$key
得到ngFor
,因为它不是结构数组的一部分,因为$key
是一个标识符,而不是firebase数据结构中的属性。
当你第一次得到它时,你能做什么push
$key
到阵列上。虽然你没有展示你如何得到infos
我认为它会是这样的。
this.api.get(`mydatabase/infos`).then(infosData => {
this.infos = infodata;
});
在返回的promise中,您可以访问$key
,然后可以将其推送到视图中使用的数组中。
this.api.get(`mydatabase/infos`).then(infosData => {
infosData.forEach((el,idx) => {
console.log(el.$key);
// Use the index as you should be pushing onto an object literal
// Of course this could be different depending how you have
// structured the data being returned for firebase which is not
// specified in your question
infos[idx].push('key') = el.$key;
});
});
然后在ngFor
的视图中使用的数组现在将具有属性info.key
,您可以将其用作onValidate(info)
方法中的标识符。
我遇到了类似的问题,后来我经历了here提供的示例代码。键值从snapshotChanges()获得。所以在这里,我使用JSX spread属性以下列方式存储每个孩子的键值。
import { Component } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Component({
selector: 'app-root',
template: `
<ul>
<li *ngFor="let item of items | async">
<input type="text" #updatetext [value]="item.text" />
<button (click)="updateItem(item.key, updatetext.value)">Update</button>
<button (click)="deleteItem(item.key)">Delete</button>
</li>
</ul>
<input type="text" #newitem />
<button (click)="addItem(newitem.value)">Add</button>
<button (click)="deleteEverything()">Delete All</button>
`,
})
export class AppComponent {
itemsRef: AngularFireList<any>;
items: Observable<any[]>;
constructor(db: AngularFireDatabase) {
this.itemsRef = db.list('messages');
// Use snapshotChanges().map() to store the key
this.items = this.itemsRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
}