rocky
rocky

Reputation: 831

How to get the value from AngularFireObject<Object>

I am learning Angular, creating basic app where i got stuck while performing db operation.

I have service to get the user from database as below

getUser(uid : String) : AngularFireObject<AppUser> {
    return this.db.object('/users/'+uid);
  }

I am calling above function from canActivate method where i need to get the user and return the property(return user.isAdmin, boolean property ) of user object. so i added below code

 canActivate() :  Observable<boolean>{
    return this.auth.user$.map(user =>  this.userService.getUser(user.uid)).map( appUser => appUser.isAdmin);
  }

In above code, i am unable to call appUser.isAdmin. can you pls help me to return isAdmin property from canActivate method . Following error is thrown

Property 'isAdmin' does not exist on type 'AngularFireObject<AppUser> 

Suggest a better solution please

Upvotes: 0

Views: 381

Answers (3)

mohammed moqran
mohammed moqran

Reputation: 1

Change

getUser(uid : String) : AngularFireObject<AppUser> {
  return this.db.object('/users/'+uid);
}

to

get(uid:string):Observable<any> {
  return this.db.object('/users/'+uid).valueChanges();
}

and

canActivate(): Observable<boolean> {
  return this.auth.user$.map(user =>  this.userService.getUser(user.uid)).map(appUser => appUser.isAdmin);
}

to

canActivate(): Observable<boolean> {
  return this.auth.user$
    .pipe(switchMap((user) => this.userService.get(user.uid)))
    .pipe(
      map((appUser) => {
        return appUser.isAdmin;
      })
    );
}

Upvotes: 0

Anjil Dhamala
Anjil Dhamala

Reputation: 1622

You can't do appUser.isAdmin because appUser is not of AppUser type where I'm assuming the isAdmin is a property of. According to this function,

getUser(uid : String) : AngularFireObject<AppUser> {
    return this.db.object('/users/'+uid);
  }

the return type is AngularFireObject. Please, follow Josie's solution to return an observable that would give you AppUser object on subscription.

Upvotes: 1

Josie G. Bigler
Josie G. Bigler

Reputation: 374

After reading some of the AngularFire documentation I think you need to turn your

getUser(uid : String) : AngularFireObject<AppUser> {
    return this.db.object('/users/'+uid);
  }

into

getUser(uid : String) : Observable<AppUser> {
    return this.db.object('/users/'+uid).valueChanges();
  }

And then you would subscribe to the observable as normal.

Upvotes: 0

Related Questions