2017-01-22 54 views
3

我正在使用Firebase和AngularFire2库构建一个Angular2应用程序。连接到Firebase数据库后,如何处理用户注销?

如何在用户注销授权连接后注销?例如,具有有效帐户的用户登录后,将与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(); 
    } 
} 

回答

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

不得不加上“如果(this.orderSubscription)回报;!”由于登录时间问题,它位于_unsubscribeFromUserOrders的顶部,但这种方式就像一种魅力。谢谢! –

相关问题