0

I have a service with this function :

this.addSubject = function(categId, data){      
 $firebase(url.child('discussions').child(categId)).$push(data).then(function (newChildRef) {
    console.log("added record with id " + newChildRef.key());
    });      
};

And I call the function in my Controller. But I want to recover the new id newChildRef.key(), to use it in my Controller. But if I make a return, there is nothing.

Is there a way to save this id ?

Or is it possible to call other function of my service in this function ?

Dayan
  • 7,634
  • 11
  • 49
  • 76
  • 1
    Can you return just the `$firebase(url.child('discussions').child(categId)).$push(data)` portion and access the key from within a `.then(...)` in your controller? – Bryan Mar 14 '15 at 23:47
  • Just a note, [AngularFire](https://www.firebase.com/docs/web/libraries/angular/quickstart.html) was 1.0.0 was recently released, and `$firebase` is now deprecated. You can use [`$firebaseObject`](https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebaseobject) and [`$firebaseArray`](https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebasearray) instead. – sbolel Mar 15 '15 at 03:39
  • @bryan I had totally forgot to try to return the `firebase(url.child('discussions').child(categId)).$push(data)`... But it works ! And @SinanBolel, i know that `$firebase` is now deprecated, but I use the 0.9.2 version :) – Valentin S. Mar 15 '15 at 15:17

1 Answers1

1

You can't return from these functions as they're part of the promise contract and will happen asynchronously in the future. What you must do instead is get your function to call a method in your controller to tell it the key that was loaded. The controller can then respond and the UI will follow. How do you get your function to know where to call?

Have the controller pass to your service the function within itself that the service should call when the result is known.

e.g.

var target = function(id) { // processes id
};

// call the function in your service passing the receiving function
service.addSubject('catid', 'data', target);

and your service will need to receive the function and do something with it

this.addSubject = function(categId, data, callback){
$firebase(url.child('discussions').child(categId)).$push(data).then(function (newChildRef) {
    console.log("added record with id " + newChildRef.key());

    // send to the callback
    callback(newChildRef.key());
  });      
};
Ashley Frieze
  • 4,993
  • 2
  • 29
  • 23