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
});
}
}
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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With