Angular how to access values from Json Array from firebase doc

Viewed 53
this.currentUser$=this.afs.doc('users/'+this.authState.uid).valueChanges().pipe();

When I am using in component.html like

{{ currentUser$|async|json}}

I am getting it like below:

{
  "photoUrl": "",
  "password": "",
  "mobileVerified": true,
  "id": "izoNRvk0moN579KqfQ1cVqNvpZJ2",
  "phone": "5544663311",
  "email": "admin@example.com",
  "name": "Rob B",
  "userRole": "admin"
}

Now for example I want to access just email or userRole, how I can do it?

2 Answers

Set the value in pipe.

currentUser$: Observable<User>;
currentUser?: User;

 :

 this.currentUser$=this.afs.doc('users/'+this.authState.uid).valueChanges().pipe(
  tap( value => {
    this.currentUser = value;
  })
 );

Then you can access each property.

{{currentUser?.email}}
{{currentUser?.userRole}}

I used the suggestions here to get the values from single document from firebase collection, but had to make a little modification for currentUser<User> to currentUser<User | undefined> and it works perfectly.

private userDoc: AngularFirestoreDocument<User>;
currentUser: Observable<User | undefined>;

and in constructor:

this.userDoc = afs.doc<User>('users/'+this.docId);
this.currentUser = this.userDoc.valueChanges();

and in component.html I can access this like

{{(currentUser|async)?.email}}
{{(currentUser|async)?.userRole}}
Related