使用angularfire2,如何编写作为字段子项生成的新密钥
我正在尝试将push生成的新密钥写入子字段中 是否可以在同一写入事务上写入?像下面这样的使用angularfire2,如何编写作为字段子项生成的新密钥,angular,key,push,angularfire2,Angular,Key,Push,Angularfire2,我正在尝试将push生成的新密钥写入子字段中 是否可以在同一写入事务上写入?像下面这样的 const evt = this.angularfire2Service.afDb.list('/path/'); evt.push({ id : <<<< key generated on push >>>>> title: newdata.title, }).then( newrec => { console.
const evt = this.angularfire2Service.afDb.list('/path/');
evt.push({
id : <<<< key generated on push >>>>>
title: newdata.title,
}).then( newrec => {
console.log('chave = ', newrec.key)
});
我建议使用firebase sdk来实现这一点。 实际上,在使用.push()时已经生成了密钥 i、 e 然后
使用angularfire2,在
event.service.ts
上,您需要
import { AngularFireDatabase } from 'angularfire2/database';
@Injectable()
export class EventService {
userKey: string;
constructor(private _fbApp: AngularFireDatabase) {}
addEvent(event) {
// creating key without pushing data
this.eventKey = this._fbApp.database.ref('/events').push().key;
// adding the key as a property to the object you will push
event.uid = this.eventKey;
// creating child node with same key and pushing data
this._fbApp.database().ref('/events').child(this.eventKey).set(event);
}
在事件.component.ts中
addEvent({ value, valid }: { value: Event; valid: boolean }) {
this._eventService.addEvent(value);
this._router.navigate(['/']);
}
请注意{value:Event;
,以防您有一个验证对象的接口
这段代码应该在推送数据之前创建一个节点键,将该键存储在变量中,并立即将该键作为属性包含在推送到节点的对象中。请注意,.child(This.eventKey)
正在使用刚创建的键作为键节点
希望这有帮助
const ref = firebase.database().ref('/path').push();
ref.set({
id: ref.key,
title: newdata.title
});
import { AngularFireDatabase } from 'angularfire2/database';
@Injectable()
export class EventService {
userKey: string;
constructor(private _fbApp: AngularFireDatabase) {}
addEvent(event) {
// creating key without pushing data
this.eventKey = this._fbApp.database.ref('/events').push().key;
// adding the key as a property to the object you will push
event.uid = this.eventKey;
// creating child node with same key and pushing data
this._fbApp.database().ref('/events').child(this.eventKey).set(event);
}
addEvent({ value, valid }: { value: Event; valid: boolean }) {
this._eventService.addEvent(value);
this._router.navigate(['/']);
}