Using Angular, I'm trying to get data from an API. The GET request seems to be successful because, when I display the GET result in the console view, I can see that I'm getting an array of the right size and with the correct values. The issue is that, when I try to read a single data from an array element, it is undefined.
export class Achat {
constructor(
public IDAchat_PK: number,
public Date: Date,
public Fournisseur: string,
public FraisLivraison: string,
public status: number
) {}
}
export class DbService {
/* Back end URL */
public Back_End_Url = "https://localhost:7198/pokegong/";
constructor(private httpClient: HttpClient) { }
public GetAchats(): Observable<Achat> {
return this.httpClient.get<Achat>(this.Back_End_Url "Achat");
}
}
export class StockComponent implements OnInit {
achats: Achat[] = [];
constructor(private dbService: DbService) {
}
ngOnInit(): void {
console.log("app-stock is initializing");
this.GetAchats();
}
GetAchats() {
/* Get stock items from Back End and fill _stock_items*/
return this.dbService.GetAchats().subscribe((data: {}) => {
this.achats = data;
console.log(this.achats[3])
console.log(this.achats[3].Fournisseur)
});
}
}
Upon execution of console.log(this.achats[3]), I can see in the console the text {idAchat_PK: 4, date: '2022-10-05T00:00:00', fournisseur: 'VISTAPRINT', fraisLivraison: 6.19, status: 2}
However, upon execution of console.log(this.achats[3].Fournisseur), I get the 'undefined' value.
All my workaround was not successful. I really don't understand how I can be able to read a full JSON record, but not a single element within this record.
Many thanks for your help.
CodePudding user response:
You got a mistake in your code. You reffered to Fournisseur
instead of fournisseur
...
JS is a case-sensitive language.
CodePudding user response:
The console log shows a lowercase fournisseur key. In your class you use a variable with a uppercase "F" (Fournisseur). So the value cannot be right converted.
I think console.log(this.achats[3].fournisseur)
will work as well.
You can map the result, too like const convertedResult = this.achats.map((data) => {return new Achat(.....);})
Greetings, Flo