I am trying to evaluate Angular 2 and I am having problems with observables.
I am trying to create a simple service that initially returns a hard coded array but wil
You can use Observable.of method.
getFleets(): Observable<IFleet[]> {
return Observable.of(this.fleet)
}
Don't forget to import of using the following line
import "rxjs/add/observable/of"; // For RxJs 5.0+
For RxJS 6.x
getFleets(): Observable<IFleet[]> {
return of(this.fleet)
}
Import statement for "of"
import { of } from "rxjs";
For this you can user BehaviorSubject
export class FleetListService {
public data: any = new BehaviorSubject('your hard coded data goes here');
getdata() {
//do your stuff
this.FleetListService.next('new data got from server');
}
}
One of the variants of Subjects is the BehaviorSubject, which has a notion of "the current value". It stores the latest value emitted to its consumers, and whenever a new Observer subscribes, it will immediately receive the "current value" from the BehaviorSubject. Behaviour subject always returns last data. For more info
This is coming a bit late, just for clarification anyways. This is how you can create a simple observable in case you want to mimic your own like promise. You do
let observable=Observable.create(observer => {
setTimeout(() => {
observer.next("data to send can be object or anything");
console.log("am done");
observer.complete(); // to show we are done with our processing
// observer.error(new Error("error message"));
}, 2000);
})
to subscribe to it is very easy
observable.subscribe((data) => {
console.log(data); // should be 'data to send can be object or anything'
});
you can also convert it to promise using toPromise() or fromPromise(observable)
operator and so on.