AngularFire2 unsubscribed to exit, database permission errors on closed subscription
I have this code here using the AngularFire2 version that I am using to grab some member from the database on one of my components.
I have a problem when I call this output from one component. I am unsubscribing, but I still get an error in the console saying Exception was thrown by user callback. Error: permission_denied at /users/uid
. I know this because I am no longer being signed and my database rules do not allow this read operation. I don't know why it is still trying to read the data if I have already unsubscribed.
constructor(private afAuth: AngularFireAuth, private db: AngularFireDatabase) {
this.user = afAuth.authState;
this.userSub = this.user.subscribe(auth => {
if (auth) {
this.member = db.object('/users/' + auth.uid);
this.dbSub = this.member.subscribe();
}
});
}
logout() {
this.dbSub.unsubscribe();
this.userSub.unsubscribe();
this.afAuth.auth.signOut()
.then(() => this.router.navigateByUrl('/login'));
}
source to share
You might try to use an RxJS object along with an operator takeUntil()
to ensure that the observable is cleared before signOut()
:
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';
export class Foo {
private ngUnsubscribe: Subject<void> = new Subject<void>();
constructor(private afAuth: AngularFireAuth, private db: AngularFireDatabase) {
this.user = afAuth.authState;
this.userSub = this.user.subscribe(auth => {
if (auth) {
this.member = db.object('/users/' + auth.uid);
this.dbSub = this.member
.takeUntil(ngUnsubscribe)
.subscribe(results => console.log(results));
}
});
}
logout() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
this.userSub.unsubscribe();
this.afAuth.auth.signOut()
.then(() => this.router.navigateByUrl('/login'));
}
}
Hope this helps!
source to share