angularngoninit

Angular fetching data on ngOnInit requires refreshing the component


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.


Solution

  • Maybe you need to subscribe to service?

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