I am working on Angular WebApi. I have a database response on localhost in JSON format.
When I run my application, I can see the array oData
. But when I reload the page then oData
becomes undefined.
How can I solve this?
Here is my code from the .ts file:
ngOnInit(): void {
this.mydataser.getDbData().subscribe(data => {
this.oData = data;
});
}
public importData() {
console.log(this.oData)
}
Here is my service:
getDbData(): Observable<DataFactory[]> {
return this.http.get<DataFactory[]>("https://localhost:44216/api/dbdata");
}
P.S. I tried to use localstorage but it does not work.
CodePudding user response:
Declare data as an empty array; if you don't do it will be undefined until the API response is completed. If you want to know when the response is actually coming just use tap. So If you want to call importData()
after API response is received then call this.importData()
method inside subscribe
like
// declare as empty array
oData = [];
buttonEnabled = false;
ngOnInit(): void {
this.mydataser.getDbData().pipe(
tap(d => this.buttonEnabled = true)
).subscribe(data => {
this.oData = data;
});
}
importData(): void{
console.log(this.o.Data);
}
In template:
<button [disabled]="!buttonEnabled">Import</button>