Attempting API calls and generating a class for the API response model, but struggling to retrieve response values. Here is my code:
In app component.ts, I have ons_list as my response object, but unable to access ons_list.success.
In home.component.ts
import { Component, OnInit } from '@angular/core';
import { getOnsService } from "../../service/getOns.service";
import { result } from "../../model/result";
import { gold } from "../../model/gold.model";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
providers: [],
})
export class HomeComponent implements OnInit {
ons_list?: gold;
ngOnInit(): void {
this.get_Ons()
}
constructor(private service: getOnsService) {
service.getOns().subscribe((response: gold) => {
this.ons_list = response;
});
console.log(this.ons_list);
}
get_Ons() {
this.service.getOns().subscribe((response: gold) => {
this.ons_list = response;
});
console.log(this.ons_list);
}
}
getOns.service.ts
import { Injectable } from "@angular/core";
import { HttpHeaders, HttpClient, HttpErrorResponse } from "@angular/common/http";
import { result } from "../model/result";
import { Observable } from "rxjs";
import { gold } from "../model/gold.model";
@Injectable({
providedIn: 'root'
})
export class getOnsService {
getheaders() {
return new HttpHeaders({
"Content-Type": "application/json",
'Authorization': 'apikey 71kRhLc4nPehMJ6iPerw4s:4qStHMIhye28Ih4HjrqqFg'
});
}
header = this.getheaders();
constructor(private http: HttpClient) { }
root_url = "https://api.collectapi.com/economy/";
getOns(): Observable<gold> {
return this.http.get<gold>(this.root_url + "goldPrice", { headers: this.header });
}
}
gold.model.ts
import { result } from "./result";
export class gold {
success?: string;
result?: result[];
}
result.model.ts
export class result {
name?: string;
buy?: number;
sell?: string;
}
home.component.html
<div class="grid">
<div class="col-3 ">
<p-card header="ONS">
<ul>
<li>
{{ons_list.success}}
</li>
</ul>
</p-card>
</div>
Error message:
https://i.sstatic.net/fjLKW.png
API service: