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

标签 angular facebook firebase promise observable

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

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

Unable to load URL: The domain of this URL is not included in the list of application domains. To download this URL, add all the domains and subdomains of your application in the Domains field applications in your application settings.

最佳答案

RxJS是一个比 Promises 更灵活、更强大的框架用于异步编程。话虽如此,使用 Observables 是一个偏好问题。或 Promises使用 Firebase API 时。
AngularFire开发是为了更轻松地将 Firebase 集成到 Angular 项目中。 AngularFire API 使用 Observables而不是 Promises ,因为 RXJS 是事实上的 Angular 异步编程标准。
如果您想提供自己的 RXJS Firebase 的 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>

关于angular - Firebase:应在 Angular 项目中使用 Promise 还是 Observable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58682482/

相关文章:

ios - Firebase 数据结构和过滤

Angular - 测试 Routerguard

android 如何从 facebook 获取用户关于我的信息

javascript - firebase 数据列表

objective-c - 如果用户的 Facebook session 有效,如何重定向到另一个 View Controller ?

ios - 使用 Facebook 应用程序时 Facebook 登录回调不起作用 - Swift

android - Firebase 作业调度程序 : Jobs that run endlessly due to an error are never scheduled again

Angular 2 在带有 Angular 路由器的 NPM 模块中延迟加载 NgModule

angular - 如何让 ngx-bootstrap datepicker 只能选择和显示月份和年份?

angular - 发生未处理的异常 : Configuration 'production' is not set in the workspace