CodexBloom - Programming Q&A Platform

AJAX call in Angular not updating the view after successful data retrieval from a REST API

πŸ‘€ Views: 246 πŸ’¬ Answers: 1 πŸ“… Created: 2025-07-11
angular ajax httpclient rxjs TypeScript

I'm converting an old project and I've encountered a strange issue with I'm facing an issue where my Angular component does not update the view after making an AJAX call to a REST API. I am using Angular 12 and the HttpClient module to fetch data. The AJAX call seems to be successful since I'm receiving a 200 OK response with the expected JSON data, but the bound properties in my template do not reflect this new data after the HTTP call completes. Here’s the relevant code snippet for my service method that makes the AJAX call: ```typescript import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DataService { private apiUrl = 'https://api.example.com/data'; constructor(private http: HttpClient) {} getData(): Observable<any> { return this.http.get<any>(this.apiUrl); } } ``` In my component, I'm subscribing to this service method: ```typescript import { Component, OnInit } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-data-view', templateUrl: './data-view.component.html', }) export class DataViewComponent implements OnInit { data: any; constructor(private dataService: DataService) {} ngOnInit() { this.dataService.getData().subscribe( response => { this.data = response; console.log('Data retrieved:', this.data); }, error => { console.error('Error fetching data', error); } ); } } ``` In my template, I am binding to `data` like so: ```html <div *ngIf="data"> <h1>{{ data.title }}</h1> <p>{{ data.description }}</p> </div> ``` The console log shows the correct data structure after the subscription, but the view does not update to display this information. I have confirmed that change detection is running, but it seems Angular is not detecting the changes. I've even tried calling `ChangeDetectorRef.detectChanges()` manually, but that didn’t resolve the issue either. I've also checked for any issues with the `ngIf` directive and confirmed that the component is correctly initialized. Has anyone encountered a similar issue, or could there be something I'm missing in the way Angular handles updates after an AJAX call? This issue appeared after updating to Typescript 3.9. What would be the recommended way to handle this? Is there a better approach?