How to return data from subscribe with Angular?

Sometimes, we want to return data from subscribe with Angular.

In this article, we’ll look at how to return data from subscribe with Angular.

How to return data from subscribe with Angular?

To return data from subscribe with Angular, we can return the map observable.

For instance, we write

export class Component {
  someMethod() {
    return this.http.get(path).map((res) => {
      return res.json();
    });
  }
}

to call http.get to make a get request to the path.

Then we call map with a callback that returns the response JSON with res.json.

We return the map observable so we can call someMethod and chain that with subscribe to listen for emitted values from map to get the response.

Conclusion

To return data from subscribe with Angular, we can return the map observable.