How to create an observable in Angular 2

前端 未结 3 695
野性不改
野性不改 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: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.

提交回复
热议问题