How to create an observable in Angular 2

前端 未结 3 690
野性不改
野性不改 2020-12-28 14:48

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

相关标签:
3条回答
  • 2020-12-28 15:06

    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";
    
    0 讨论(0)
  • 2020-12-28 15:10

    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

    0 讨论(0)
  • 2020-12-28 15:23

    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.

    0 讨论(0)
提交回复
热议问题