1

I have this function that finds an object to my database and should return it, I put a conse.log before to see if there it is the object I want to get and works correctly.

Here it is my service:

buscarUsuario(email: string){

 return this.http.post(`${URL}/user/email`, email)
          .subscribe(resp => {      
          //Here i can see the object and works      
          console.log(resp['usuario']);
          
          //This return doesn't work
          return resp['usuario'];
          
         }); 
         
  

}

And here it is the function of my backend, this one I tested it in Postman and works correctly:

userRoutes.post('/email', async(req: Request, res: Response) => {

const usuario = await Usuario.findOne({email: req.body.email});

res.json({
    ok: true,
    usuario
});

});

So, can anyone tell me how to return that object? Please :)

3 Answers 3

1

You cannot return value from .subscribe() method. .subscribe() returns Subscription to appropriate Observable. The question is what you want to achieve?

Sign up to request clarification or add additional context in comments.

2 Comments

So, how do I return that object?
All depend on what you want to do with this object. Observable concept bases on reactivity. So you can create stream buscarUsuario(email: string){ return this.http.post(${URL}/user/email, email) } stream$ = buscarUsario("[email protected]") This stream you can use in your template with async pipe Alternatively, you can call await this.http.post(${URL}/user/email, email).toPromise() and grab value.
0

The problem is that you are returning a function. A better approach to return the object is to use something like a promise.

For example

function buscarUsuario(email: string){
  return new Promise((resolve, reject) => {
    this.http.post(`${URL}/user/email`, email)
             .subscribe(resp => {      
             //Here i can see the object and works      
             console.log(resp['usuario']);
             
             resolve(resp['usuario'])
            }); 
  })      

now you can access the object in 1 of 2 ways either by calling .then() or using async await

first method

...
buscarUsuario(...)
   .then(usuario => {
         // usuario is your object
   })
   .catch(err => { throw err })

a cleaner way would be using async await

let usuario = await buscarUsuario(...)

keep in mind for the 2nd way your function which includes that line must be async

for example

async function test() {
    let usuario = await buscarUsuario(...)
}

EDIT

function buscarUsuario(email: string){
    return this.http.post(`${URL}/user/email`, email).toPromise()
}

or

function buscarUsuario(email: string){
  return new Promise((resolve, reject) => {
    this.http.post(`${URL}/user/email`, email)
             .toPromise()
             .then(resp => {      
             //Here i can see the object and works      
             console.log(resp['usuario']);
             
             resolve(resp['usuario'])
            }); 
  })     

The main difference is the 2nd method will return the value instead of the object

async function test() {
    let usuario = await buscarUsuario(...)
}

Something like this should work. Try it and let me know the results

12 Comments

I tried right now the second way, the async function, and now returns me a null object, at the console.log says null too
did you wrap this.http.post with a promise like I did?
I checked my answer I forgot to add quotation here resolve(resp[usuario]) it should be resolve(resp['usuario'])
Yes, I figured it out before, I tried and stills saying null.
Okay try return this.http.post("${URL}/user/email", email).toPromise()) make sure to use ` instead of "
|
0

The right way would be to not subscribe in the service method, but to return the observable:

buscarUsuario(email: string){
  return this.http.post(`${URL}/user/email`, email)
          .pipe(map(resp => resp['usuario']))        
}); 

Then you can subscribe to the method, from any other place, e.g. your component:

componentMethod() {
  this.myService.buscarUsuario.subscribe(usuario => this.usuario = usuario);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.