I have a "HomeComponent", that displays the user name in the UI.
The user name is read from a json file using a service.
I have the service provided in the AppComponent (parent to HomeComponent) and reused in HomeComponent
AppComponent.html
<router-outlet></router-outlet>
AppComponent.ts
export class AppComponent {
constructor(private userService: UserService) {
this.userService.fetchUserDetails();
}
}
UserService.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../models/user';
import 'rxjs/add/operator/first';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class AppStateManagerService {
private userDetails: User;
private initializeUser(data) {
this.userDetails = new User();
this.userDetails.name = data.username;
this.userDetails.id = data.userid;
}
constructor(private http: HttpClient) {}
async fetchDeviceDetails() {
let response = await this.http
.get('./app/config/user.json')
.first()
.toPromise();
this.initializeUser(response);
return this.userDetails;
}
getUserDetails() {
return this.userDetails;
}
}
HomeComponent.html
<div>{{user && user.name}}</div>
HomeComponent.ts
export class HomeComponent {
user: User;
constructor(private userService: userService) {
this.user = this.userService.getUserDetails();
}
}
The problem I face here is, the HomeComponent gets initialized first, before the JSON parsing is complete, that is before fetchUserDetails() is complete in AppComponent, the getUserDetails() in HomeComponent is called and the user.name is null in the HTML, before being populated in the service.
Is there a way to sync this up? Without using Observable?