Unable to figure out correct EventEmitter or Observable Syntax in Angular2 Services

限于喜欢 提交于 2019-11-27 20:10:19

Actually it's almost the same thing, there a few changes

 createUser(user: any): any {
    return new Observable.create(observer => {
      this.ref.createUser(user, function(error, userData) {
        if (error) {
          observer.error(error);
          console.log("Error creating user:", error);
        } else {
          observer.next('success');
          observer.complete();
          console.log('Successfully created user account with uid:', userData.uid);
        }
       });  
    })
  }

And then you can suscribe to it (subscribe is the equivalent of then).

Here's a plnkr with an example using Observables

constructor() {
    this.createUser({}).subscribe(
        (data) => console.log(data), // Handle if success
        (error) => console.log(error)); // Handle if error
}

EventEmitter on the other hand is a Subject (documentation differs a little bit since angular2 moved to the last version, but it's still understandable).

_emitter = new EventEmitter();
constructor() {
    // Subscribe right away so we don't miss the data!
    this._emitter.toRx().subscribe((data) => console.log(data), (err) => console.log(err));
}
createUser(user: any) {
    this.ref.createUser(user, function(error, userData) {
        if (error) {
          this._emitter.throw(error);
          console.log('Error creating user:", error');
        } else {
          this._emitter.next(userData);
          this._emitter.return(); This will dispose the subscription
          console.log('Successfully created user account with uid:', userData.uid);
        }
    })  
}   

Here's a plnkr with an example using EventEmitter.

The difference in super short : Observable starts emitting the data when it finds subscribers; Subject emits info whether there are subscribers or not.

Note

In the EventEmitter example I used toRx(). This exposes the Subject but it's being refactored and we won't need toRx() anymore.

Useful resources Updated

RxJS In-Depth by Ben Lesh in AngularConnect's 2015 conference.

Thanks to Rob Wormald for pointing out this

You can see Sara Robinson's talk and her demo app and see it running here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!