I have a weird bug in my angular project. When I fetch my data with a mock API from local data, everything is working fine, but when I switch to Online API and fetch data with Observable subscribe method, data is not updated in my angular template view. It will be updated only when I call detector.detectChanges() method.
In brief, For somehow when using online API, two-way data binding is only working when I call detectChanges.
For example imagine below scenario:
data = [some data here...]
getData(): Observable<any> {
return of(this.data);
}
when I call this method in my .ts file and fetch data with it, angular template will be updated automatically. But when i switch to below code:
getData(): Observable<any> {
let url = `${this.API_URL}/fetchData/`;
return this.http.get(url);
}
and fetch data in my angular .ts file like below:
this.myService.getData().subscribe(result => {
this.myData = result;
// this.detector.detectChanges();
})
myData variable is not updated in the angular template unless I uncomment // this.detector.detectChanges() method.
And detectChanges is imported from below library of angular:
private detector: ChangeDetectorRef,
Can anyone help me please to overcome this bug? It's really annoying and my code now has a lot of detectChanges everywhere right after any code that needs two-way data binding!
thanks in advance
Update
my .html file
<table class="table table-bordered table-striped table-responsive"
style="display: inline-table;">
<thead>
<tr style="left: 0;">
<th><span>test</span></th>
</tr>
</thead>
<tbody>
<tr style="left: 0;" *ngFor="let d of myData">
<td>{{d.test}}</td>
</tr>
</tbody>
</table>
this.myService.getData()directly tothis.myData, making it anObservable, and useasyncpipe on it (e.g.myData | async) in the template?changeDetection: ChangeDetectionStrategy.OnPushin your@Componentdecorator config. Delete it, if you want angular CD to dirty checking for you after something async event happened.