我正在我的网站上创建一个写入实时数据库的联系表格。使用 Cloud Functions,我想通过向自己发送一封包含联系人详细信息的电子邮件来响应数据库条目。
我已经确认我只发送了一次有效负载,并且数据正在完美地写入数据库。我遇到的问题是 onWrite 响应数据库的每一行条目,例如我发送姓名、电子邮件、公司和消息,因此,我的函数调用了 4 次。我不会重写数据库,我知道它会执行另一个调用。每次调用时都会收到一行数据作为单个值,我没有得到文档中“承诺”的所有值的对象。我也尝试过 onCreate,它甚至没有被调用。
我被误导了吗?这是预期的行为吗?任何帮助表示赞赏。
编码...
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);
});
我的班级发布到“消息”...
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<any[]>;
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);
}
}