Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display service variable in component

This is an Angular 6, Firestore, and Firebase project. I want to display different user information pending who is logged in. I'm using Firebase for authentication and Firestore to hold additional data about my users, such as their displayNames. My databases look something like this.

Authentication (Firebase)

  1. email = [email protected]
    userId = 101
  2. email = [email protected]
    userId = 202

Firestore Users Collection

  1. email = [email protected]
    userId = 101
    displayName = oneDisplayName

  2. email = [email protected]
    userId = 202
    displayName = twoDisplayName

I have a user.service.ts that manages both of these in my app. Using this service, what I want to do is (a) when someone is logged in, pull their displayName from the Firestore Users Collection (b) set displayName equal to a variable in my service (c) inject my service into any component and show displayName in the component.html. I am able to grab displayName in the service, but can't successfully transfer it to a component.

Here is the code. What is the better way to do this?

user.service.ts

## imports and @injectable are up here ## 

export class UserService {
  usersCollection: AngularFirestoreCollection<User>;
  users: Observable<User[]>;
  user: Observable<firebase.User>;
  username: string;

  constructor(private afAuth: AngularFireAuth,
              private router: Router,
              private afs: AngularFirestore) {
      this.usersCollection = this.afs.collection('users');
      this.users = this.usersCollection.valueChanges();
      this.user = afAuth.authState;

      this.user.subscribe(user => {
          if (user === null) {
            this.loggedIn = false;
          } else {
            this.loggedIn = true;
            this.usersCollection.doc(`${user.uid}`).ref.get()
              .then((doc) => {
                this.username = doc.data().displayName; <-- WORKS IN SERVICE BUT NOT COMPONENT ####
              });
          }
      });
   }

navbar.component.ts

import { UserService } from '../user.service';

export class NavbarComponent {
  username;

  @Component({
    providers: [ UserService ]
  })

  constructor(private userserv: UserService) {
    this.username = this.userserv.username; <-- UNDEFINED
  }
}

navbar.component.html

<nav class="navbar">
  {{ username }}
<nav>
like image 890
John Avatar asked Jun 02 '26 12:06

John


1 Answers

To always retrieve the up-to-date value from the service, define the property as a getter in the component class:

public get displayName(): string {
  return this.userserv.username;
}
like image 175
ConnorsFan Avatar answered Jun 04 '26 03:06

ConnorsFan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!