7

I want to return value (any data) from service to component as an observable. After a couple of digging into observables found following solution:

class AppService {
    getData(value) {
        // do we have any other best way to return value as an observable
        return Observer.create((observer) => {
            observer.next(value);
        });
    }
}

class AppComponent implements OnInit {
    ngOnInit() {
        this.dataService$ = this.appService.getData().subscribe((data) => {
            // do some task with data
        });
    }
}
2
  • 4
    return of(value) Commented Mar 5, 2019 at 9:14
  • 2
    You already found the answer, what's the question here ? Commented Mar 5, 2019 at 9:26

3 Answers 3

9

Just return like below

import { Observable, of } from 'rxjs';

...

getData(value) : Observable<any> {
   // Simple way of sending value using of operator.
   return Observable.of(value);
}

Hope this help!

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

2 Comments

thanks it worked, do you know if I need to do either way means returning observable as a value;
yes you need to return observable as value so that you can subscribe to obsevable to get data in component
7

Use of like so:

import { of } from 'rxjs';
...
return of(value);

which is equivalent to:

return new Observable(obs => obs.next(value));

However, if you want to convert a given value (e.g. a Promise, an Observable-like, an Array, an iterable or an array-like object) you may want to use from:

import { from } from 'rxjs';
...
return from(value);

Comments

2

Here's what I do

In your service file :

First I declare my observable this way

  myObs: BehaviorSubject<any> = new BehaviorSubject([]);

In a method you can set your datas into your obs :

var myArray = [1,2,3,4,5];
this.myObs.next(myArray);

If you want your "controller" to subscribe this obs, in your service, just expose a getter :

public getMyObs(){
return this.myObs.asObservable()
}

And in your "controller" you can call it this way :

 ngOnInit() {

this.myService.getMyObs().subscribe(datas => {
    Do What you want with your datas
  }
}

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.