Search code examples
javascriptfirebasegoogle-cloud-functionsangularfire2

How can I pass data from angular to my cloud function and get a response back?


Currently, I try to pass data to a cloud function from my angular frontend and want to receive the value of a boolean which gets true if the process is successful.

my index.ts file:

export const someTesting = functions.https.onCall(async (data) => {

  let success = false;
  const testData = {...data};

  await admin.firestore().collection('collection').add(testData).then(() => {
    return success = true;
  });
});

my angular.ts file

async callCloudFunction(testData: TestData) {
  const sendDataToCloudFunctions = this.fun.httpsCallable('someTesting');

  // here I pass the data to the cloud function
  sendDataToCloudFunctions(testData);

  // here I want to consolte.log() the boolean success ...
}

Would be great if someone could show me how to do this. Thank you!


Solution

  • Callable type Cloud Functions need to return a promise that resolves with the data object to send to the client. Right now, your function is returning nothing. The one return statement you have is just returning from the callback function you passed to then.

    You also shouldn't mix async/await syntax with then. Just use one or the other, as they have the same purpose.

    If all you want to do is return a boolean success status after the database operation is complete, then do this:

    export const someTesting = functions.https.onCall(async (data) => {
    
      let success = false;
      const testData = {...data};
    
      await admin.firestore().collection('collection').add(testData);
      return { success: true };
    });
    

    To get the result in your app, you will need to handle the promise returned by sendDataToCloudFunctions just like any other promise.