In my project I have a service that should load local database when the app is started. For that the function GetData()
is used. I try to use it by calling at the ngOnInit()
lifecycle hook. It logs the result in the console, but the property datum
appears to be unchanged.
However, if I add GetData()
method to a button, the property changes and data is displayed in the console as intended.
All sources that I looked through suggest that the right way to load the DB if I need it right away is to use ngOnInit()
hook, that's why I don't wat to call GetData()
when some event from the DOM is fired.
Component
export class AppComponent implements OnInit {
datum;
constructor(private searchService: SearchService){ }
getData(){
this.searchService.getData().subscribe(
data => {
this.datum = data[0];
console.log(this.datum);},
err => console.log("E", err)
);
}
ngOnInit(){
this.getData();
}
title = 'app';
}
HTML
<div style="text-align:center">
<h1>
Welcome to {{title}}!!
Data: {{datum | json}}
</h1>
<button (click)="getData()">Click Me</button>
App loaded

Button clicked

EDIT
Implementation of getData()
with setTimeout()
as suggested by AlexKhymenko
getData(){
this.searchService.getData().subscribe(
data => {
setTimeout(() =>{
this.datum = data[0];
});
console.log(this.datum);},
err => console.log("E", err)
);
}