找出正确的EventEmitter或可观察到的语法在Angula

找出正确的EventEmitter或可观察到的语法在Angula

本文介绍了无法找出正确的EventEmitter或可观察到的语法在Angular2服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个困难时期为在Angular2服务使用观测实例/指南的方式找到了。有工具和HTML模板是 EventEmitter 结合,但似乎不适合的服务。

I'm having a hard time finding much in the way of examples/guides for using observables in an Angular2 service. There is stuff for html templates binding with EventEmitter but that doesn't seem right for a service.

一大驱动的主题是从Angular2承诺越来越远,但我似乎无法得到新的语法正确。

One of the big driving themes is getting away from Promises in Angular2 but I can't seem to get the new syntax correct.

我在干什么


  • 我有一个 FirebaseAuth服务可以注入到其他
    服务或组件。

  • 我有做一个异步调用的函数
    火力点,在我的例子来创建一个用户

  • 我要回一个观测(更换承诺)的其他服务可以用来做其他事情一样创建一个配置文件时,这是解决

  • I have a FirebaseAuth Service that can be injected into otherservices or components.
  • I have a function that does an async call tofirebase, in my example to create a user
  • I want to return a Observable(to replace the promise) that other services can use to do other things like create a profile when this is resolved

我很好,如果承诺是这个例子中,最好的解决办法,但我想弄清楚在观测方法

I'm fine if promises are the best solution for this example but I'd like to figure out what the Observable Way is.

我的服务:

/*DS Work on firebase Auth */
import {Injectable} from 'angular2/angular2';

@Injectable()
export class FirebaseAuth {
  ref = new Firebase('https://myfirebase.firebaseio.com');
  //check if user is logged in
  getAuth(): any {
    return this.ref.getAuth();
  }

  //register a new user
  createUser(user: any): Promise<any> {
    return new Promise((resolve, reject) => {
      this.ref.createUser(user, function(error, userData) {
        if (error) {
          reject(error);
          console.log('Error creating user:", error');
        } else {
          resolve(userData);
          console.log('Successfully created user account with uid:', userData.uid);
        }
       })
    })
  }
};

我将如何改写这个使用观测和/或EventEmitter?

推荐答案

其实它几乎同样的事情,有一些变化

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);
        }
       });
    })
  }

然后您就可以 suscribe 到它(订阅相当于再)。

下面是一个使用观测量的例子

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 ,另一方面是的(documentation不同于一点点,因为angular2移动到最后一个版本,但它仍然是可以理解的)。

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);
        }
    })
}

下面是一个使用EventEmitter一个例子。

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.

注意

在我使用的EventEmitter例如梅花头()。这暴露了主题 正的重构,我们赢了'T需要梅花头()了。

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

有用的资源 更新

会议。

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

感谢罗布沃莫尔德指出了该

您可以看到和她的并看到它运行

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

这篇关于无法找出正确的EventEmitter或可观察到的语法在Angular2服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:40