Reputation: 831
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
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
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
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