I am very new to Firebase Functions. I created a Function called getQuizById(). The function returns the Quiz in JSON format. If I call the function directly via a URL, it returns the JSON data as expected. e.g.:
https://us-central1-example-f1afa.cloudfunctions.net/getQuizById?id=ef8GwUuHt8X4XQJBIgZf
Since that is working, I need to call that same function from my Angular 17 app, here is the code I am using for that:
import { Functions, httpsCallable } from '@angular/fire/functions';
private functions: Functions = inject(Functions);
constructor(private route: ActivatedRoute) {
// get the id fdrom the url
const id = this.route.snapshot.params['id'];
const getQuizById = httpsCallable(this.functions, 'getQuizById');
getQuizById({ id: 'ef8GwUuHt8X4XQJBIgZf' }) // <- HARD CODED ID JUST FOR TESTING
.then((result) => { // <- ERROR HERE
console.log(result);
});
}
I took this code example straight from the docs on the Firebase website, so I assume I’m doing it correctly. Still, the Function itself is not receiving the passed in ID parameter, so it is failing with code 400 (“Quiz ID is required”).
Here is the code from the Function itself, in case it helps.
// The Cloud Functions for Firebase SDK to create Cloud Functions and triggers.
const { logger } = require("firebase-functions");
const { onRequest } = require("firebase-functions/v2/https");
const { cors } = require("cors")({ origin: true });
// The Firebase Admin SDK to access Firestore.
const { initializeApp, applicationDefault, cert } = require("firebase-admin/app");
const { getFirestore, Timestamp, FieldValue, Filter } = require("firebase-admin/firestore");
initializeApp();
const db = getFirestore();
exports.getQuizById = onRequest({ cors: true }, async (request, response) => {
const quizId = request.query.id;
if (!quizId) {
response.status(400).send("Quiz ID is required");
return;
}
try {
const quizDocref = db.collection("quizzes").doc(quizId);
const quizDoc = await quizDocref.get();
if (!quizDoc.exists) {
response.status(404).send("Quiz not found. ID: " + quizId);
return;
}
response.status(200).json(quizDoc.data());
} catch (error) {
console.error("Error getting quiz document:", error);
response.status(500).send("Internal Server Error");
}
});