You can save the loaded user in the lcoalStorage after the first load and then just read it on the following accesses.
This is a simple solution to learn. But in a real application scenario you shouldn't have "infinite time" cache like this. And must have a way to update the cache sometimes.
Change the service class to :
@Injectable()
export class AccountService {
get userAccount() {
return JSON.parse(localStorage.getItem('user'));
};
constructor(private _httpClient: HttpClient) {
}
getAllUSerInfoNormal(forceBanckendCall: boolean): Observable<UserAccount> {
if (this.userAccount && !forceBackendCall) {
return of(this.userAccount);
}
return this._httpClient.get<UserAccount>(Constants.apiRoot + 'account/accountInfo')
.pipe(
tap(user => localStorage.setItem('user', JSON.stringify(user)))
);
}
then the component class to:
@Component({
selector: 'app-main-view',
templateUrl: './main-view.component.html',
styleUrls: ['./main-view.component.scss']
})
export class MainViewComponent implements OnInit {
private account: UserAccount;
private isDataLoaded = false;
constructor(private _router: Router,
private _accountService: AccountService) {
setInterval(() => {
this.updateResources();
}, 1);
}
ngOnInit() {
this._accountService.getAllUSerInfoNormal().subscribe(account => this.userAccount = account);
}
updateResources(){
}
}
then in your component template place a *ngIf="userAccount"
in the elements that you want to be loaded just after the user is present.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…