从Angular 4组件调用Firebase云功能

时间:2018-06-08 10:53:00

标签: angular typescript firebase google-cloud-functions

我正在使用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功能?

1 个答案:

答案 0 :(得分:3)

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

  

部署HTTP功能后,您可以通过自己的方式调用它   唯一的网址。该URL按顺序包括以下内容:

function toogleGeoButtons() {
    // toggle function
    console.log("toggled")
}
geoSettings = {
    timeout: 1000 * 10,
    maximumAge: 1000 * 60,
    enableHighAccuracy: true
}
navigatorPermisstion();
function navigatorPermisstion() {
    navigator.permissions.query({
        name: 'geolocation'
    }).then(function(result) {
        if (result.state == 'granted') {
            toogleGeoButtons();
            // console.log(result.state);
            getLocation();
        } else if (result.state == 'prompt') {
            // console.log(result.state);
            navigator.geolocation.getCurrentPosition(revealPosition, positionDenied, geoSettings);
        } else if (result.state == 'denied') {
            toogleGeoButtons();
            // console.log(result.state);
        }
        result.onchange = function() {
            navigatorPermisstion();
        }
    });    
}

function revealPosition(position) {
    console.log(position)
}
function positionDenied(positionError) {
    console.log(positionError)
}

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

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

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

最后,我建议您观看Firebase团队的以下视频,其中详细说明了如何编写HTTP云功能,特别是如何向呼叫者发送响应:

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

您可能会发现需要稍微调整一下代码。