LandSharks LandSharks -4 years ago 77
TypeScript Question

Mimic a HTTP Observable return with subject

I have created an angular 4 service that currently uses an HTTP request to return an Observable of type Comment.

return this.http.post(targetUrl, JSON.stringify({ 'Text': comment.Text, 'ThreadId': threadId }), options)
.map(this.extractData)
.catch(this.handleError);


I want this service to return a local data I constructed into a variable when I am on a local host. However, I am unable to just return my local variable of type comment since it is not an Observable. How do I go about making this local variable into an observable?

Answer Source

Just pass in your variable as an argument to Observable.of method. It will return an observable.

*You can accomplish the same with Subject, but I don't see why you would use one in this scenario. Anyway,

var subject = new Subject();
subject.next(variable);
subject.asObservable();

Rx.Observable.of(...args) Converts arguments to an observable sequence.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/of.md

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download