关于angular:Firebase Cloud Function onWrite触发多次触发

Firebase Cloud Function onWrite trigger firing multiple times

我正在我的网站上创建一个联系表,该联系表写入实时数据库。我想使用Cloud Functions通过向自己发送一封包含联系人详细信息的电子邮件来响应数据库条目。

我已经确认我只发送一次有效负载,并且数据被完美地写入数据库。我遇到的问题是onWrite会响应数据库的每一行输入,例如我发送姓名,电子邮件,公司和消息,因此,我的函数被调用了4次。我不会重写数据库,但我知道该数据库会执行另一次调用。每次调用都会收到一行数据作为单个值,我没有在文档中得到所有值都为'promised \\'的对象。我还尝试了onCreate,甚至没有被调用。

我误会了吗?这是预期的行为吗?任何帮助表示赞赏。

代码...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendContactMessage = functions.database
  .ref('/messages/{pushKey}')
  .onWrite(event => {
    const snapshot = event.data;
    // Only send email for new messages.
    if (!snapshot.exists()) { return null; }

    const val = snapshot.val();

    console.log(val);
  });

我的课程发布到\\'messages \\'...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AngularFireDatabase, AngularFireObject } from 'angularfire2/database';
import * as firebase from 'firebase/app';

export interface Item { name: string; email: string; message: string; html: string; date: string }

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.scss']
})
export class ContactComponent {
      public rForm: FormGroup;
      public post: any;
      public message: string = '';
      public name: string = '';
      public company: string = '';
      public email: string = '';
      itemRef: AngularFireObject;
      item;

  constructor(private fb: FormBuilder, public db: AngularFireDatabase) {
    this.createForm();
    this.itemRef = db.object('messages');
    this.item = this.itemRef.valueChanges();
  }

  createForm() {
    this.rForm = this.fb.group({
      name: [null, Validators.required],
      email: [null, Validators.compose([Validators.required, Validators.email])],
      message: [null, Validators.compose([Validators.required, Validators.minLength(15)])],
      validate: ''
    });
  }

  sendMessage(post) {

    this.name = post.name;
    this.email = post.email;
    this.message = post.message;

    const item: Item = {
      name: post.name,
      email: post.email,
      message: post.message,
      html: `You were contacted from your website by ${post.name}. They said"${post.message}". You can contact them back on ${post.email}`,
      date: Date()
    };

    this.itemRef.update(item);
  }
}


我怀疑有人会像我一样愚蠢,但是,我正在写入数据库中的同一位置。仅存在1个条目,因此我正在"更改" 4个数据项,因此我将触发4个onWrite事件。

我通过在数据库中的唯一文件夹下创建一个新条目来解决此问题。