Reputation: 1500
I´m working with Angular 4, Firebase Database and Cloud Functions. The question: How can I call a Firebase Function on click from my component?
Just what I try to do: Sending a test email with emailjs on button click.
My code:
functions/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 <[email protected]>",
to: "someone <[email protected]>, another <[email protected]>",
cc: "else <[email protected]>",
subject: "testing emailjs"
}, function(err, message) { console.log(err || message); });
})
My component
sendTestEmail() {
// From here I want to call the "sendMail" function from Firebase to send an email.
}
So: How can I call a Firebase Function from my component?
Upvotes: 1
Views: 2398
Reputation: 83103
You are using an HTTP Cloud Function, therefore you have to trigger it by calling a specific URL, as explained in the documentation: https://firebase.google.com/docs/functions/http-events#invoke_an_http_function
After an HTTP function is deployed, you can invoke it through its own unique URL. The URL includes the following, in order:
- The region in which your function is deployed - Your Firebase project ID - cloudfunctions.net - The name of your function
So, in your case, the URL to invoke sendMail() is:
https://us-central1-<your-project-id>.cloudfunctions.net/sendMail
You should use the HttpClient service to trigger this call.
Finally, I would suggest you watch the following video from the Firebase team which details how HTTP Cloud Functions shall be written, and in particular how to send a response to the caller:
https://www.youtube.com/watch?v=7IkUgCLr5oA
You will probably see that you need to slightly adapt your code accordingly.
Upvotes: 3