Categories
Angular Answers

How to return data directly from an Observable with Angular?

Spread the love

Sometimes, we want to return data directly from an Observable with Angular.

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

How to return data directly from an Observable with Angular?

To return data directly from an Observable with Angular, we can return an observable that lets us get the data.

For instance, we write

//...
export class Component implements OnInit, AfterViewInit {
  //...
  getSomething() {
    return this._restService
      .addRequest("object", "method")
      .run()
      .subscribe(
        (res) => {
          // ...
        },
        (err) => {
          console.error(err);
        }
      );
  }
  //...
}

to add the getSomething that returns the observable returned by subscribe.

We get the response data from the subscribe callback and do what we want with it.

Conclusion

To return data directly from an Observable with Angular, we can return an observable that lets us get the data.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *