Angular fetching data on ngOnInit requires refreshing the component

239 Views Asked by At

I wanted to assign a fetched data to a variable but the variable logs as null unless I refresh the page.

I currently have this:

  ngOnInit(): void {
    this.fetchLocalUser();
  }

  fetchLocalUser() {
    this.user = this.userService.getLocalUser();
  }
}

but when I log or print the user in the html, it returns null unless I refresh the page.

2

There are 2 best solutions below

0
Evgeny Gurevich On BEST ANSWER

Maybe you need to subscribe to service?

fetchLocalUser() {
  this.userService.getLocalUser()
    .subscribe(data => this.user = data);
}
0
Nick Felker On

I have a Firebase web app which does something similar. In my case I have a user service implemented with a callback pattern that each page can subscribe to.

There's a small callback abstraction since the service lives longer than each page, so there are times when I may want to manually refresh user data from the server.

ngOnInit(): void {  
    this.firebaseListener = this.firebase.subscribeUser(user => {
      if (user) {
        this.user = user
        // do user stuff...
      }
    })
  }
  subscribeUser(callback: (u: Users.Doc) => void) {
    const listener = this.userSubject.subscribe(callback)
    callback(this.userData)
    return listener
  }

  async refreshUser() {
    const userDoc = await getDoc(doc(this.db!, 'users', this.user!.uid))
    const data = userDoc.data() as Users.Doc
    this.userData = data;
    this.userSubject.next(this.userData)
  }