【问题标题】:Firebase: Should Promise or Observable be used in an Angular project?Firebase:应该在 Angular 项目中使用 Promise 还是 Observable?
【发布时间】:2020-02-29 02:57:46
【问题描述】:

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

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

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

【问题讨论】:

    标签: angular facebook firebase promise observable


    【解决方案1】:

    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>
    

    【讨论】:

      猜你喜欢
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      • 2018-11-13
      • 1970-01-01
      • 2017-07-09
      • 2016-07-22
      • 1970-01-01
      相关资源
      最近更新 更多