Hassan Raza
Hassan Raza

Reputation: 679

How to return data from subscribe module function angular 7

I am new to angular 7 and there is a problem to return data from a component function. It may not the way to ask a question because I have less understanding regarding angular 7.

Here is my component function:

getUserStatus

getUserStatus(){
  this.chatService.newUserJoined().subscribe(data=>{
    this.statuses = data;
  });
  return this.statues;
}

The chatService get the data from service and now I just want to return the status from this function either may be the status could be true or false. I need to return the data from this function I tried but it gives me undefined.

Upvotes: 0

Views: 149

Answers (1)

asimhashmi
asimhashmi

Reputation: 4378

You can't return data directly from subscribe

Why?

Because your function is using Observable and Observable is asynchronous i.e. the data will not be available immediately and your function will not wait for data and will complete its execution and return null and it should not be the way to treat an Observable because you are mixing your synchronous call of function with asynchronous code.

The proper way to do this is to return Observable from that function and then call subscribe on it. You can do it like this:

getUserStatus() {
  return this.chatService.newUserJoined()
}

And in your caller function you can can do this like this

getUserStatus().subscribe(data=>{
    // work with data returned
  });

More information on Observables here

Upvotes: 2

Related Questions