people.
I have a Angular application which I am integrating with a node.js server. It works like this:
- A service is injected in the component
- The component calls the getAccountData() function from the service, which is a http.get request.
- The service interacts with the node server that retrieves the data from the data model.
Here is the code for the account.component.ts:
import { Component, inject } from '@angular/core';
import { AccountService } from '../../services/account.service';
import { NgIf } from '@angular/common';
@Component({
selector: 'app-account',
imports: [NgIf],
templateUrl: './account.component.html',
styleUrl: './account.component.css'
})
export class AccountComponent {
account = inject(AccountService);
accountData: any;
isLoaded = false;
ngOnInit() {
this.account.getAccountData().subscribe(data => {
this.accountData = data;
this.isLoaded = true;
});
}
}
And here is the code for the account.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class AccountService {
private baseUrl = 'http://localhost:3000/account';
constructor(private http: HttpClient) {}
getAccountData(): Observable<any> {
return this.http.get<any>(this.baseUrl);
}
}
Finally, the HTML:
<p>account works!</p>
<div> {{ accountData }} </div>
<div> {{ accountData.name }} </div>
The problem I am currently facing is that the accountData renders correctly in the HTML:
{ "name": "Felipe", "cardLimit": 3750, "totalEarnings": [], "totalExpenses": [] }
But not the name. In the console, it is saying that "cannot read properties of undefined (reading 'name')". But I did not understand why the accountData could be rendered but not it's property.
I also added a print of the page.
Could anyone explain to me why this is happening? I understand it has something to do with asynchronous requests and Angular rendering the page before executing all subscribe, but I do not understand the behavior I explained.
I tried to use ngIf, but maybe not correctly.