无法在 Angular2 服务中找出正确的 EventEmitter 或 Observable 语法 [英] Unable to figure out correct EventEmitter or Observable Syntax in Angular2 Services

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

问题描述

我很难找到在 Angular2 服务中使用 observable 的示例/指南.有一些 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 中远离 Promises 是一大驱动主题,但我似乎无法正确理解新语法.

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 服务,可以注入到其他服务或组件.
  • 我有一个函数可以异步调用firebase,在我的示例中创建用户
  • 我想返回一个 Observable(替换承诺),其他服务可以使用它来做其他事情,例如在解决此问题时创建配置文件
  • I have a FirebaseAuth Service that can be injected into other services or components.
  • I have a function that does an async call to firebase, 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

如果 Promise 是此示例的最佳解决方案,我很好,但我想弄清楚 Observable Way 是什么.

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

我将如何重写它以使用 Observable 和/或 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);
        }
       });  
    })
  }

然后你就可以订阅(subscribe相当于then).

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

这是一个 plnkr 和一个使用 Observables 的例子

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 另一方面是 Subject(文档有点不同自从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);
        }
    })  
}   

这是一个 plnkr 和一个使用 EventEmitter 的例子.

Here's a plnkr with an example using EventEmitter.

超短的区别:Observable在找到订阅者时开始发射数据;无论是否有订阅者,主题都会发出信息.

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

注意

在 EventEmitter 示例中,我使用了 toRx().这暴露了 Subject它正在重构,我们不需要 不再使用 toRx().

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 作者:Ben Lesh 在 AngularConnect 2015 年 会议.

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

感谢 Rob Wormald 指出这一点

您可以看到莎拉·罗宾逊的演讲和她的演示应用 并在此处

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆