Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Firebase Cloud Function directly from you angular project

I am new to firebase and is trying to understand how to call a firebase cloud function directly from my angular app. I have previously used angularfire2 for doing Firebase stuff but it seems that angularfire2 does not have support for cloud functions so now I am left lost and does not know how to do it.

I have looked at the documentation but I can not really understand how, exactly, I am supposed to call the cloud function from one of my service.ts files. The example from Firebase Doc is displayed below. I wonder how I get the "functions" reference within one of my angular service.ts files?

functions.httpsCallable("addMessage").call(["text": inputField.text]) { (result, error) in
  if let error = error as NSError? {
    if error.domain == FunctionsErrorDomain {
      let code = FunctionsErrorCode(rawValue: error.code)
      let message = error.localizedDescription
      let details = error.userInfo[FunctionsErrorDetailsKey]
    }
    // ...
  }
  if let text = (result?.data as? [String: Any])?["text"] as? String {
    self.resultField.text = text
  }
}

Do I need to import something in the app.module.ts file or what am I supposed to do?

Any help is much appreciated! Thanks!

like image 751
iSebbeYT Avatar asked May 15 '18 12:05

iSebbeYT


People also ask

How do I access Firebase functions?

Run firebase login to log in via the browser and authenticate the firebase tool. Go to your Firebase project directory. Run firebase init firestore . For this tutorial, you can accept the default values when prompted for Firestore rules and index files.


2 Answers

Maintainer here, Angularfire shipped the AngularFireFunctions module in RC 9 the other day. See the AngularFire changelog entry here.

Note that as of RC 8, you'll need to upgrade to at least Firebase 5.0.2 and rxjs 6. rxjs-compat will help it you still have dependencies on rxjs 5.

like image 191
James Daniels Avatar answered Oct 16 '22 22:10

James Daniels


I ran into this issue as well and the answer from James didn't really answer my question on where I could find a good example on how it would look in Angular. However, within the firebase repostiory a README with small, but enough documentation can be found.

This is pretty much how compact you can go:

import { AngularFireFunctions } from '@angular/fire/functions';

constructor(
    private fns: AngularFireFunctions
  ) {}

  addMessage(): Observable<any> {
    const addMessage = this.fns.httpsCallable('addMessage'); 
    return addMessage({text: "test"});
  }
like image 25
Ruben Szekér Avatar answered Oct 16 '22 22:10

Ruben Szekér