首页 > 解决方案 > 从 Angular 4 组件调用 Firebase 云函数

问题描述

我正在使用 Angular 4、Firebase 数据库和云函数。问题:如何在我的组件中单击时调用 Firebase 函数?

正是我尝试做的:单击按钮时使用 emailjs 发送测试电子邮件。

我的代码:

函数/src/index.ts

import * as functions from 'firebase-functions';
const emailjs = require("emailjs/email");

export const sendMail = functions.https.onRequest((request, response) => {
  var email     = require("./path/to/emailjs/email");
  var server    = email.server.connect({
    user:    "username",
    password:"password",
    host:    "smtp.your-email.com",
    ssl:     true
  });

  // send the message and get a callback with an error or details of the message that was sent
  server.send({
    text:    "i hope this works",
    from:    "you <username@your-email.com>",
    to:      "someone <someone@your-email.com>, another <another@your-email.com>",
    cc:      "else <else@your-email.com>",
    subject: "testing emailjs"
  }, function(err, message) { console.log(err || message); });
})

我的组件

sendTestEmail() {
  // From here I want to call the "sendMail" function from Firebase to send an email.
}

那么:如何从我的组件调用 Firebase 函数?

标签: angulartypescriptfirebasegoogle-cloud-functions

解决方案


您正在使用HTTP Cloud Function,因此您必须通过调用特定 URL 来触发它,如文档中所述:https ://firebase.google.com/docs/functions/http-events#invoke_an_http_function

部署 HTTP 函数后,您可以通过其自己的唯一 URL 调用它。URL 按顺序包括以下内容:

- The region in which your function is deployed
- Your Firebase project ID
- cloudfunctions.net
- The name of your function

因此,在您的情况下,调用 sendMail() 的 URL 是:

https://us-central1-<your-project-id>.cloudfunctions.net/sendMail

您应该使用 HttpClient 服务来触发此调用。


最后,我建议您观看 Firebase 团队的以下视频,该视频详细介绍了如何编写 HTTP 云函数,特别是如何向调用者发送响应:

https://www.youtube.com/watch?v=7IkUgCLr5oA

您可能会看到您需要相应地稍微调整您的代码。


推荐阅读