# Angularfire2 logout

**URL:** <https://forum.ionicframework.com/t/angularfire2-logout/110003>\
**Category:** ionic-v3\
**Created:** [October 26, 2017, 6:17am UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003 "2017-10-26T06:17:31Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![angusallman](https://avatars.discourse-cdn.com/v4/letter/a/848f3c/32.png) [@angusallman](https://forum.ionicframework.com/u/angusallman)\
**Post date:** [October 26, 2017, 6:17am UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/1 "2017-10-26T06:17:32Z")

</div>

Hi there,  
I’m making a login for my app using angularfire2 for the user authentication and I’m having a bit of trouble logging out.

The login works perfectly and so does the registration, but when I come to log out I get this error:

```auto
Error: permission_denied at /profile/AhGIYnvAz4akV94D6RGy26rhCcl1: Client doesn't have permission to access the desired data.

```

I’m not sure why it’s happening, I’ve had a look around google, from what I can see it’s something to do with not unsubscribing from an observable? but I can’t track it down or fix it.

here is my code to call my dashboard page (leaving that page causes the error to occur.)

```auto
export class DashboardPage {

  profileData: AngularFireObject<Profile>;
  profile: any;

  constructor(private toast: ToastController,
    private afAuth: AngularFireAuth,
    private afDatabase: AngularFireDatabase,
    public navCtrl: NavController,
    public navParams: NavParams,
    private fb: FireBaseProvider) {
  }

  ionViewDidLoad() {
    this.afAuth.authState.take(1).subscribe(data => {
      if(data && data.email && data.uid){
        this.toast.create({
          message: `welcome to APP_NAME, ${data.email}`,
          duration: 3000
        }).present();

        this.profileData = this.afDatabase.object(`profile/${data.uid}`);
          this.profileData.valueChanges().subscribe(data=>{
          this.profile = data;
        });

      }
    });
  }

  ionViewWillLeave(){
  }

  logout(){
    this.fb.logout().then(() => {
      this.navCtrl.setRoot('LoginPage');
    }
    );
  }

```

then here is my logout function from my firebase provider

```auto
  async logout(): Promise<any>{
    return this.afAuth.auth.signOut();
  }

```

it seems to log me out just fine but it it just throws that error soon after.

Thanks for the help!

---

<div class="post-metadata">

**Author:** ![AaronSterling](https://avatars.discourse-cdn.com/v4/letter/a/51bf81/32.png) [@AaronSterling](https://forum.ionicframework.com/u/AaronSterling)\
**Post date:** [October 26, 2017, 7:13am UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/2 "2017-10-26T07:13:20Z")

</div>

There’s something active on your page that is making a request of Firebase. The request continues when logged out, violating the database rules. Unsubscribe from all Observables before calling auth.signout().

---

<div class="post-metadata">

**Author:** ![angusallman](https://avatars.discourse-cdn.com/v4/letter/a/848f3c/32.png) [@angusallman](https://forum.ionicframework.com/u/angusallman)\
**Post date:** [October 26, 2017, 10:13am UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/3 "2017-10-26T10:13:44Z")

</div>

Thanks for the reply! do you know if there’s a way to figure out which one? because I’ve tried unsubscribing from the initial auth observable and from the one getting the profile within that one, and I’ve not had any luck, it just stopped the page loading. I also tried it on the IonViewWillLeave method and it dodn’t seem to work either! I’m a bit stuck on this one, if you want I can provide a bit more code to give you a better idea what’s going on? Thanks

---

<div class="post-metadata">

**Author:** ![QGangler](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/qgangler/32/113105_2.png) [@QGangler](https://forum.ionicframework.com/u/QGangler)\
**Post date:** [October 26, 2017, 11:26am UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/4 "2017-10-26T11:26:57Z")

</div>

In the example you provided you have

```auto
this.profileData.valueChanges().subscribe(data=>{
    this.profile = data;
});

```

You have to unsubscribe to this before you call `auth.signOut()`.  
I usually have multiple `subscribe` so I have a array of them in my pages (`_subs: Subscription[]`)

```javascript
let sub: Subscription = this.profileData.valueChanges().subscribe(data=>{
    this.profile = data;
});
this._subs.push(sub);

```

And then before you log out or go to another page you can do

```javascript
for(let sub of this._subs) {
    if (sub) {
        sub.unsubscribe();
    }
}
// call your logout function here

```

There might be a better way (or a cleaner) way to do it (What do you think @AaronSterling?)

---

<div class="post-metadata">

**Author:** ![angusallman](https://avatars.discourse-cdn.com/v4/letter/a/848f3c/32.png) [@angusallman](https://forum.ionicframework.com/u/angusallman)\
**Post date:** [October 26, 2017, 12:45pm UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/5 "2017-10-26T12:45:35Z")

</div>

Hey, thanks this is a really good way of dealing with it! Apologies, I’m a bit new to Ionic and angular in general. I’ve tried implementing it and this is what I’ve got:

```auto
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireObject, AngularFireDatabase } from 'angularfire2/database';
import {AngularFireAuth} from 'angularfire2/auth';
import { Profile } from '../../models/profile';
import { ToastController } from 'ionic-angular';
import { LoginPage } from '../login/login';

import { FireBaseProvider } from '../../providers/firebase/firebase';

@IonicPage()
@Component({
  selector: 'page-dashboard',
  templateUrl: 'dashboard.html',
})
export class DashboardPage {

  profileData: AngularFireObject<Profile>;
  profile: any;
  
  _subs: Subscription[] = [];

  constructor(private toast: ToastController,
    private afAuth: AngularFireAuth,
    private afDatabase: AngularFireDatabase,
    public navCtrl: NavController,
    public navParams: NavParams,
    private fb: FireBaseProvider) {
  }

  ionViewDidLoad() {
    let authSub = this.afAuth.authState.take(1).subscribe(data => {
      if(data && data.email && data.uid){
        this.toast.create({
          message: `welcome to APPNAME, ${data.email}`,
          duration: 3000
        }).present();

        this.profileData = this.afDatabase.object(`profile/${data.uid}`);
        let sub: Subscription = this.profileSub = this.profileData.valueChanges().subscribe(data=>{
          this.profile = data;
        });
        this._subs.push(sub);
      }
    });
    this._subs.push(authSub);
  }

  ionViewWillLeave(){
      // authSub.unsubscribe();
      // profileSub.unsubscribe();
  }

  logout(){
    for(let sub of this._subs) {
      sub.unsubscribe();
    }
    this.fb.logout().then(() => {
      this.navCtrl.setRoot('LoginPage');
    }
    );
  }

}

```

I’m probably missing something really simple, but it doesn’t seem to be working and still throws that error.

Thanks!

---

<div class="post-metadata">

**Author:** ![AaronSterling](https://avatars.discourse-cdn.com/v4/letter/a/51bf81/32.png) [@AaronSterling](https://forum.ionicframework.com/u/AaronSterling)\
**Post date:** [October 26, 2017, 1:08pm UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/6 "2017-10-26T13:08:49Z")

</div>

> [@QGangler](#):
>
> There might be a better way (or a cleaner) way to do it (What do you think @AaronSterling?)

I removed “subscribe” from my pages, and only use it in providers. I use the async pipe in pages. That way, Angular handles the unsubscribes for me.

Also, I don’t directly listen to the streams from providers. Instead, I put them in a meta-observable with a gate, sort of like `listenIfAuth<T>(obs: Observable<T>): Observable<T> { // return an observable that checks if af.auth is truthy, and if so, returns the value of the profile stream}`. That way, it’s physically impossible to forget to unsubscribe from a stream before logout.

---

<div class="post-metadata">

**Author:** ![QGangler](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/qgangler/32/113105_2.png) [@QGangler](https://forum.ionicframework.com/u/QGangler)\
**Post date:** [October 26, 2017, 2:43pm UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/7 "2017-10-26T14:43:49Z")

</div>

> [@AaronSterling](#):
>
> listenIfAuth\<T\>(obs: Observable\<T\>): Observable\<T\>

This is next level stuff (love it).

I bit too next level to understand what you mean even (at least for me). So if I get you right this `listenIfAuth` function is only used in providers and is the “in-between” firebase observables and your subscribes in your providers.

And the pseudo code for it would be

```javascript
listenIfAuth<T>(obs: Observable<T>): Observable<T> {
    if (isAuthed) {
        return obs;
    }
    return ???; //What do you put here?
}

```

---

<div class="post-metadata">

**Author:** ![AaronSterling](https://avatars.discourse-cdn.com/v4/letter/a/51bf81/32.png) [@AaronSterling](https://forum.ionicframework.com/u/AaronSterling)\
**Post date:** [October 26, 2017, 2:54pm UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/8 "2017-10-26T14:54:00Z")

</div>

My last post was a bit vague, sorry. There are two ways the OP’s error can occur. Either you start listening to something after you’re not allowed to, or you continue listening to something after you aren’t allowed to. An approach like your subs array takes care of the second issue. But the first issue still matters, for example if you have a provider that might initiate a subscribe request asynchronously with login or logout. (Ask yourself this about your code: what if a user logs in and then logs out before your subscriptions start? Do you catch that behavior? Or are you assuming nobody logs out until your subscriptions are live and in the subs array?)

So listenIfAuth is a way to make sure that an unauthorized subscription does not start.

---

<div class="post-metadata">

**Author:** ![QGangler](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/qgangler/32/113105_2.png) [@QGangler](https://forum.ionicframework.com/u/QGangler)\
**Post date:** [October 26, 2017, 3:05pm UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/9 "2017-10-26T15:05:34Z")

</div>

Totally in agreement with you :).

That’s why I asked more precision on the function because I didn’t fully understand what it did (thank again for the clarification).

You probably missed it in my previous post but what should `listenIfAuth` return if you’re not authed? `obs.complete()`?  
Like this?

```javascript
listenIfAuth<T>(obs: Observable<T>): Observable<T> {
    if (isAuthed) {
        return obs;
    }
    return obs.complete();
}

```

---

<div class="post-metadata">

**Author:** ![AaronSterling](https://avatars.discourse-cdn.com/v4/letter/a/51bf81/32.png) [@AaronSterling](https://forum.ionicframework.com/u/AaronSterling)\
**Post date:** [October 26, 2017, 3:09pm UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/10 "2017-10-26T15:09:35Z")

</div>

I return `Observable.from([])` usually, but you could choose any dummy value, or a special value you recognize like `Observable.from(['not authorized'])` if you want you page to have the option to tell the user something.

---

<div class="post-metadata">

**Author:** ![QGangler](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/qgangler/32/113105_2.png) [@QGangler](https://forum.ionicframework.com/u/QGangler)\
**Post date:** [October 26, 2017, 3:27pm UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/11 "2017-10-26T15:27:34Z")

</div>

So to get back to OP question he would have to create a profileProvider like so

```javascript
export class ProfileProvider {

    constructor(private afAuth: AngularFireAuth, private afDtatabase: AngularFireDatabase){}

    getProfile(): Observable<Profile> {
        return listenIfAuth<Profile>(this.afDatabase.object(`profile/${this.afAuth.auth.currentUser.uid}`).valueChanges());
    }

    //Should be put in another provider
    listenIfAuth<T>(obs: Observable<T>): Observable<T> {
        if (this.afAuth.auth.currentUser) {
            return obs;
        }
        return Observable.from([]);
    }
}

```

Correct?

---

<div class="post-metadata">

**Author:** ![AaronSterling](https://avatars.discourse-cdn.com/v4/letter/a/51bf81/32.png) [@AaronSterling](https://forum.ionicframework.com/u/AaronSterling)\
**Post date:** [October 26, 2017, 3:31pm UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/12 "2017-10-26T15:31:11Z")

</div>

I think the OP is making a much simpler error somewhere. I wouldn’t recommend he follow what I’m saying to you yet. I think it would be best to develop more of a feel for Observables before getting too fancy with them. No offense intended to the OP. But to answer your question, yes that looks fine.

---

<div class="post-metadata">

**Author:** ![angusallman](https://avatars.discourse-cdn.com/v4/letter/a/848f3c/32.png) [@angusallman](https://forum.ionicframework.com/u/angusallman)\
**Post date:** [October 26, 2017, 3:48pm UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/13 "2017-10-26T15:48:04Z")

</div>

No offense taken! no worries, that looks like a great way to deal with it so seriously thank you, I’ll keep trying, and give your method a go too and see how it goes! Thanks both of you for helping with this, I’ll update once I’ve solved it.

---

<div class="post-metadata">

**Author:** ![neilbo21](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/neilbo21/32/119158_2.png) [@neilbo21](https://forum.ionicframework.com/u/neilbo21)\
**Post date:** [February 13, 2018, 1:15am UTC](https://forum.ionicframework.com/t/angularfire2-logout/110003/14 "2018-02-13T01:15:42Z")

</div>

> [@angusallman](#):
>
> export class DashboardPage {
> 
> profileData: AngularFireObject\<Profile\>;  
> profile: any;  
> profileSub: Subscription;
> 
> constructor(private toast: ToastController,  
> private afAuth: AngularFireAuth,  
> private afDatabase: AngularFireDatabase,  
> public navCtrl: NavController,  
> public navParams: NavParams,  
> private fb: FireBaseProvider) {  
> }
> 
> ionViewDidLoad() {
> 
> ```
> this.profileSub = this.afAuth.authState.take(1).subscribe(data =&gt; {
> if(data && data.email && data.uid){
> this.toast.create({
> message: `welcome to APP_NAME, ${data.email}`,
> duration: 3000
> }).present();
> 
> this.profileData = this.afDatabase.object(`profile/${data.uid}`);
> this.profileData.valueChanges().subscribe(data=&gt;{
> this.profile = data;
> });
> 
> }
> });
> 
> ```
> 
> }
> 
> ionViewWillLeave(){  
> this.profileSub.unsubscribe();  
> }
> 
> logout(){  
> this.fb.logout().then(() =\> {  
> this.navCtrl.setRoot(‘LoginPage’);  
> }  
> );  
> }

Hey @angusallman the way I got around this was to assign the Observable to a subscription class variable, then on the IonViewWillLeave page lifecycle, unsubscribe to this.
