Firebase:在Angular项目中应使用Promise还是Observable?

时间:2019-11-03 16:55:55

标签: angular facebook firebase promise observable

我刚刚开始学习Angular。如果我使用Firebase进行用户授权,那么使用PromiseObservable更好吗?

如果尝试通过Facebook登录时出现错误,我将如何更改URL:

  

无法加载URL:此URL的域未包含在应用程序域列表中。要下载此URL,请在应用程序设置的“域”字段应用程序中添加应用程序的所有域和子域。

1 个答案:

答案 0 :(得分:0)

RxJS是一个比Promises更为灵活和强大的框架,用于异步编程。话虽如此,使用Firebase API时优先使用ObservablesPromises

AngularFire的开发旨在使将Firebase集成到Angular项目中变得更加容易。 AngularFire API使用Observables而非Promises,因为RXJS是事实上的Angular异步编程标准。

如果您想为Firebase提供自己的RXJS API,一种选择是创建Angular服务。下面的示例显示了如何包装Firebase函数signInWithCustomToken,该函数返回Promise<UserCredential>,并将其转换为返回Observable<UserCredential>

firebase-auth.service.ts

import { Injectable, Optional } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import * as firebase from 'firebase/app'
import 'firebase/auth'

import { BehaviorSubject } from 'rxjs'
import { concatMap } from 'rxjs/operators'


@Injectable({
  providedIn: 'root'
})
export class FirebaseAuthService {
  public app: firebase.app.App;
  public auth: firebase.auth.Auth;
  public user$: BehaviorSubject<firebase.User> = new BehaviorSubject(null);

  // Note: FirebaseConfig is a class to enable injecting the Firebase app 
  // initialization params when providing the service in app.module.ts.
  constructor(@Optional() fb_config: FirebaseConfig, private http: HttpClient) {
    // https://firebase.google.com/docs/reference/js/firebase.app.App
    this.app = firebase.initializeApp(fb_config);
    this.auth = firebase.auth(this.app);

    this.auth.onAuthStateChanged(
      (user: firebase.User) => {
        if (user) {
          this.user$.next(user);
          console.log('User signed in');
        } else {
          this.user$.next(null);
          console.log('User signed out');
        }
      },
      (error: firebase.auth.Error) => {
        // handle error
      }
    )
  }

  public signInWithCustomToken(uid: string, secret_auth_code: string): 
      Observable<firebase.auth.UserCredential> {
    const params = new HttpParams()
      .set('uid', uid)
      .set('secret', secret_auth_code)
    return this.http.get('/get-custom-token', {params: params}).pipe(
      concatMap((json: any) => from(this.auth.signInWithCustomToken(json['custom_token'])))
    )
  }

  // ...
}

组件

@Component({
  moduleId: module.id,
  selector: 'my-component',
  templateUrl: 'my.component.html',
  styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
  constructor(private authService: FirebaseAuthService) {}
  // ...
}

模板

<ng-container *ngIf="( authService.user$ | async ) as user">
  <div>Hello {{user.displayName}}</div>
</ng-container>