3
votes

In Ionic(AngularFire2) application, for every page i need to get Firebase User UID, to get related data from Firebase database. For example, on Firebase there is a node('/users') and its key is FireBase Auth User UID.

  {
  "users" : {
    "LYW6i8sTbWauCvkXULIbszIWOdm1" : {
      "cellPhone" : "123321",
      "name" : "Name1",
      "userType" : "0"
    },
    "i4KSAzO2UhakowLKOZCa0ZeohRH3" : {
      "cellPhone" : "43343",
      "name" : "Name2",
      "userType" : "1"
    }
  }
}

I am using observables to get the UID, for every page again and again. I think there will be lots of subscriber and everytime ionic application makes request to Firebase Auth Server to get user UID ?

For example.

export class AccountProfilePage {

      user = {} as User
  constructor(public navCtrl: NavController, public navParams: NavParams, 
    private afDb:AngularFireDatabase, private afAuth:AngularFireAuth) {
  }

  updateProfile(){
      this.afAuth.authState.subscribe(authState=>{
        this.afDb.object('users/'+authState.uid).update({
          cellPhone:this.user.cellPhone
        })
      })
  }
}

Is it the correct way ?

1
You should create a service and store your uid in the service, the service created once while you inject it - mohamad rabee

1 Answers

0
votes

Create a service which is included in the Providers section of your app.module.ts. This way the service keeps its state across the whole app.

app.module.ts

@NgModule({
  providers: [
    AuthService
  ]
})
export class AppModule {}

auth.service.ts

@Injectable()
export class AuthService {
  private uid: string;

  setUid(uid: string): void {
    this.uid = uid;
  }

  getUid(): string {
    return this.uid;
  }
}

When the user logs into the application do setUid(usersUid) then on any page you can include the auth.service in the constructor and do a getUid and it will get the UID out of the service.

export class AccountProfilePage {
    constructor(private authService: AuthService) {}

    someMethod() {
      this.authService.getUid(); // Returns UID
    }
}