Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value as an observable in angular 6

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
        });
    }
}
like image 380
upgoingstar Avatar asked Mar 05 '19 09:03

upgoingstar


2 Answers

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!

like image 107
TheParam Avatar answered Nov 14 '22 22:11

TheParam


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);
like image 41
Eliya Cohen Avatar answered Nov 14 '22 23:11

Eliya Cohen