简体   繁体   English

使用angularfire2,如何编写作为字段子级生成的新密钥

[英]With angularfire2, how to write new key generated as an field child

I'm trying to write the new key generated on push inside an child field. 我正在尝试在子字段内编写在push上生成的新密钥。

Is it possible to write on the same write transaction? 是否可以在同一写入事务上进行写入? something like below... 像下面这样

const evt = this.angularfire2Service.afDb.list('/path/');
evt.push({
    id : <<<< key generated on push >>>>>
    title: newdata.title,
 }).then( newrec => {
        console.log('chave = ', newrec.key)
});

as workaround, I can write as: 作为解决方法,我可以这样写:

.then( newrec => {
     console.log('chave = ', e.key);
     this.angularfire2Service.afDb.object('/path/+newrec.key).update({
        id: newrec.key
     });
});

I would suggest using firebase sdk for that. 我建议为此使用firebase sdk。 Indeed, key is already generated when using .push() ie 确实,使用.push()时已经生成了密钥,即

import * as firebase from 'firebase';

Then 然后

const ref = firebase.database().ref('/path').push();

ref.set({
    id: ref.key,
    title: newdata.title
});

With angularfire2, on your event.service.ts , you need to... 使用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);
}

In your event.component.ts ... 在您的event.component.ts ...

addEvent({ value, valid }: { value: Event; valid: boolean }) {
  this._eventService.addEvent(value);
  this._router.navigate(['/']);
}

Notice the {value: Event; 请注意{value: Event; in case you have an interface to validate your object. 如果您有一个接口来验证您的对象。

This code should create a node key right before you are pushing the data, storing that key in a variable, and right away including the key as a property in the object you are pushing to the node. 此代码应在推送数据之前立即创建节点密钥,将其存储在变量中,并立即将密钥作为属性包含在要推送到节点的对象中。 Notice the .child(this.eventKey) is using the just created key as the key node. 请注意, .child(this.eventKey)使用刚创建的密钥作为密钥节点。

Hope this helps!!! 希望这可以帮助!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM