Within my Angular project, I am working with two distinct components.
parent.component.ts
mypromise = this.httpClient.get<any>('http://localhost').toPromise()
parent.component.html
<app-children #child [promise]="mypromise"></app-children>
<button (click)="child.update()">Update now!</button>
child.component.ts
@Input promise: Promise<any>
ngOnInit(){
this.fetchPromiseData()
//results:
//[{id: 1, text: 'abc'}, {id: 2, text: 'abcd'}]
}
update(){
this.fetchPromiseData()
//expected:
//[{id: 1, text: 'abc'}, {id: 2, text: 'abcd'}, {id: 3, text: 'new data'}]
//results:
//[{id: 1, text: 'abc'}, {id: 2, text: 'abcd'}]
//still displaying outdated results from the initial call
}
fetchPromiseData(){
this.promise
.then(data=>console.log(data)) //here I log the results in the console
.catch(e=>console.log(e))
}
When the component initializes, the promise resolves with the expected data. However, upon triggering the update
function by clicking the Update now!
button, the promise continues to return the initial results from ngOnInit()
, rather than the updated data from the backend.
Is it possible to update the promise to fetch the latest data from the backend? How can I achieve this?