Angular Problem Firestore - The function does not return any value

0

I'm having a problem with the following function.

 retornaCantidadActual(itemProducto) {

this.prodserv.getProdObservable(itemProducto).subscribe(dataprod => {
  const xxprod = dataprod;
  console.log('Funcion retornaCantidadActual =====>', xxprod[0].cantidadActual);
  return xxprod[0].cantidadActual;
});

}

This function is within an Angular 6 component and is using firebase. As you can see, the console log that is inside the function responds correctly or is taking the value well. The getProdObservable is in the service and returns an observable with a single record that is the product passed by parameter to the function. The problem is when I call this function from another place in the program because it returns to me in console "undefined" and obviously does not take any value, but I should return the value it shows internally, I do not understand what I'm doing wrong. I thank you in advance and send a cordial greeting. Atte Marcelo.

    
asked by Marcelo Lavandeira 08.07.2018 в 03:30
source

1 answer

0

In summary: You can not get the number of just one, because you are doing asynchronous work. You have to use the service that returns the Observable and subscribe to do what you need in the place you need it.

It's not like you're doing something wrong. You may not be seeing it the right way.

You must take into account that you are doing an asynchronous job (which does not have an exact moment of execution). All network calls are asynchronous and you will have to use Observable , Promise or some type of callback for when the call is resolved. You must begin to think asynchronously (there are functions that will be executed within a short time, when the call is resolved).

Since you are working with angularfire2 I recommend you read about Observable , but if Firestore also works with Promise so you can read about that too.

For your function, take into account that you can have Observable and Subcription . A Observable is an object to which you can subscribe and obtain emitted values. A Subcription is the object that contains the function that will be executed when values are issued in Observable .

A Observable can have several Subcription pasted.

In your retornaCantidadActual function, what you are actually returning is the Subscription .

So what you have to do is use the Service that returns the Observable when you need it. There are no shortcuts for this. You have to work asynchronously.

    
answered by 10.07.2018 / 17:17
source