2017-01-22 48 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的頂部,但這種方式就像一種魅力。謝謝! –

相關問題