【问题标题】:How do you handle a user logout after connection to Firebase db?连接到 Firebase db 后如何处理用户注销?
【发布时间】:2017-01-23 10:35:13
【问题描述】:

我正在使用 Firebase 和 AngularFire2 库构建一个 Angular2 应用程序。

在建立授权连接后用户注销时如何处理?例如,具有有效帐户的用户登录,连接到我的 Firebase 数据库的“订单”节点,然后用户注销。

我在控制台中收到以下错误,这很有意义。但是我应该如何捕捉这个错误或以其他方式防止它呢?

错误:

FIREBASE WARNING: Exception was thrown by user callback. Error: permission_denied at /orders: Client doesn't have permission to access the desired data.

相关代码(我认为):

@Injectable()
export class OrderService {

  private orders$: FirebaseListObservable<any>;
  private _pendingOrders$: BehaviorSubject<any> = new BehaviorSubject(null);
  private _activeOrders$: BehaviorSubject<any> = new BehaviorSubject(null);

  constructor(
    private af: AngularFire,
    private auth: AuthService) {
    this.auth.isAuthed
      .subscribe((value: boolean) => {
        if (this.auth.isAuthed.value) {
          const userId = this.auth.getUserId();
          this._subscribeToUserOrders(userId);
        } else {
          // Somehow unsubscribe here, perhaps?
        }
      });
  }

  _subscribeToUserOrders(userId) {
    const query = {
      orderByChild: 'userId',
      equalTo: userId
    };

    this.orders$ = this.af.database
      .list(`orders`, query);

    this.orders$.subscribe((orders) => {
      // Load pending orders
      this._pendingOrders$.next(orders.filter(o => o.status === 'PENDING'));

      // Load active orders
      this._activeOrders$.next(orders.filter(o => o.status === 'ACTIVE'));
    });
  }

  get pendingOrders() {
    return this._pendingOrders$.asObservable();
  }

  get activeOrders() {
    return this._activeOrders$.asObservable();
  }
}

【问题讨论】:

    标签: angular firebase firebase-realtime-database angularfire2


    【解决方案1】:

    this.orders$.subscribe 的调用将返回一个RxJS Subscription

    import { Subscription } from 'rxjs/Subscription';
    
    private ordersSubscription: Subscription;
    ...
    this.ordersSubscription = this.orders$.subscribe(...);
    

    你可以用它来取消订阅(你可能也想从你的主题中发出null):

    if (this.auth.isAuthed.value) {
      const userId = this.auth.getUserId();
      this._subscribeToUserOrders(userId);
    } else {
      this._unsubscribeFromUserOrders();
    }
    ...
    _unsubscribeFromUserOrders() {
      this.ordersSubscription.unsubscribe();
      this.orders$ = null;
      this._pendingOrders$.next(null);
      this._activeOrders$.next(null);
    }
    

    【讨论】:

    • 必须添加“if(!this.orderSubscription) return;”由于登录时间问题,到 _unsubscribeFromUserOrders 顶部,但这就像一个魅力。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多