Angular 2 - Return data directly from an Observable

Angular 2 - Return data directly from an Observable

angular 8 observable example
return value from subscribe angular 6
angular observable data services
angular 6 observable example
how to get value outside typescript subscribe function
angular observable map
rxjs observable
angular return observable

I've been banging my head against this one trying to figure it out, and no amount of documentation I've been able to read has given me an answer to my question.

I have a service which is speaking directly to an API and returning an observable event which under normal circumstances I would subscribe to and do what I want with the data, however in a secondary service which utilizes the requests from the restful service, I need to be able to return values from the request.

getSomething() {
    return this._restService.addRequest('object', 'method').run()
        .subscribe(
            res => {
                res;
            },
            err => {
                console.error(err);
            }
        );
}

returnSomething() {
    return this.getSomething();
}

In the quick example above, I want to know if there is any way I can return res from getSomething() within returnSomething(). If it's not achievable in this way, what is the alternative? I will add that the _restService is pretty heavily relied upon and I don't really want to start messing with that.


Since http calls and the like are async, you get an Observable instead of a synchronous value returned. You have to subscribe to it, and in the callback in there you get the data. There is no way around that.

One option would be to place your logic in the subscribe call

getSomething() {
    return this._restService.addRequest('object', 'method').run()
        .subscribe(
            res => {
                // do something here
                res;
            },
            err => {
                console.error(err);
            }
        );
}

But the way I like doing it is to add a callback, to inject the logic from outside (maybe a component, maybe another service):

getSomething(callback: (data) => void) {
    return this._restService.addRequest('object', 'method').run()
        .subscribe(
            res => {
                callback(res);
            },
            err => {
                console.error(err);
            }
        );
}

And in your component or wherever:

this._yourService.getSomething((data) => {
    // do something here
    console.log(data);
});

typescript - Angular 2, Since http calls and the like are async, you get an Observable instead of a synchronous value returned. You have to subscribe to it, and in the callback in there  Angular 2 embraces elements of reactive programming, a paradigm focused on how data flows through a web application. To follow the reactive approach, we use Observables to build services and components that can react to changes in data across our application.


I didn't use this myself, but I believe it should work in theory (:

// service.ts
getSomething() {
  let subject: Subject = new Subject();
  this._restService.addRequest('object', 'method').run()
    .subscribe(subject);
  return subject;
}

// this can be removed (;
returnSomething() {
  return this.getSomething();
}

// component.ts
ngOnInit() {
  this.service.returnSomething()
    .subscribe(res => console.log(res), err => console.log(err));
}

Check subject docs for more info. You can use different types of subject, for example BehaviorSubject has value property you can access...

ngOnInit() {
  // if you use BehaviorSubject
  this.service.returnSomething().value
}

Here's the working plunker...

Using observables to pass values, The subscribe() call returns a Subscription object that has an unsubscribe() When the consumer unsubscribes, clean up data ready for next subscription. return observable that emits three values const myObservable = of(1, 2, 3); // Create  The Observable isn’t an Angular specific feature, but a new standard for managing async data that will be included in the ES7 release. Angular uses observables extensively in the event system and the HTTP service. Getting your head around observables can be quite a thing, therefore i’m here to explain it the easy way.


I had a similar issue. My solution was to convert the observable into a promise with .toPromise() (and use async - await to return it and catch errors). You can convert your code into something like:

 async getSomething() {
     try{
         return await this._restService.addRequest('object', 'method').run().toPromise()
      } catch (err){
       console.error(err);
	  }
  }

How to build Angular App with Observable Data Services, An observable data service is an Angular injectable service that can be used to provide data to The data service can then be used directly in the templates using the What this type of subject does it that it will return upon subscription the last value of the stream, Pitfall #2 - avoid duplicate HTTP calls. In this blog we’ll be focussing on a very specific aspect of the Angular ecosystem, known as Observables. Our main focus will be to retrieve data from an API by making use of Observables and to display the data in an HTML page. This blog post will only cover high-level detail elements of all topics discussed.


Understanding, creating and subscribing to observables in Angular, When version 2 of Angular came out, it introduced us to observables. all you have to do is just wait until it comes straight into your inbox. If you come from the world of promises this is a key difference as promises always return only one value. The function is a Producer of data, and the code that calls the  Note that a next () function could receive, for instance, message strings, or event objects, numeric values, or structures, depending on context. As a general term, we refer to data published by an observable as a stream. Any type of value can be represented with an observable, and the values are published as a stream.


Using Observables in Angular 4 to get data from an API service , The Angular JS framework has gained a lot of popularity over the last couple of years Observables represent 0 or more values that either return immediately or​  An observable data service is an Angular injectable service that can be used to provide data to multiple parts of the application. The service, that can be named a store can be injected in any place where the data is needed:


Angular 2 HTTP Requests with Observables ― Scotch.io, Use Angular 2's HTTP and observables to handle asynchronous calls. git clone https://github.com/angular/quickstart scotch-http # Enter into directory cd commentsUrl) // and calling .json() on the response to return data  Learn to use angular HttpClient service to fetch data from online REST APIs and return it as Observable object/array. Upon any data event, the subscribers of observable will react. Table of Contents HTTPClient Setup Create service which return Observable Create observer which subscribe to Observable View HTML Template Demo HTTPClient Setup To use HTTPClient service, […]