Angular中TS2532错误:无法获取API响应值问题求助
无法获取API响应值,访问
ons_list.success报错 问题描述
调用API接口并生成响应模型类后,定义ons_list作为响应对象,但无法访问ons_list.success,浏览器报错:Cannot read properties of undefined (reading 'success')。
代码片段
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>
错误信息
浏览器控制台报错:Cannot read properties of undefined (reading 'success'),页面无法正常渲染ons_list.success的值。
API响应结构
API返回的响应格式如下:
{ "success": true, "result": [ { "name": "Gram Altın", "buy": 1269.12, "sell": 1269.89 } ] }
解决方案
1. 修复异步请求时序问题
console.log(this.ons_list)放在subscribe外部会先于API响应执行,此时ons_list还是undefined。需要把日志移到subscribe回调内部,同时去掉构造函数里的重复API调用:
constructor(private service: getOnsService) {} get_Ons() { this.service.getOns().subscribe((response: gold) => { this.ons_list = response; console.log(this.ons_list); // 此时能拿到正确数据 }); }
2. 修正模型类的类型错误
API返回的success是布尔值,但gold模型里定义为string类型,类型不匹配会导致数据绑定异常,修改gold.model.ts:
import { result } from "./result"; export class gold { success?: boolean; // 改为boolean类型 result?: result[]; }
3. 模板添加空值保护
Angular渲染模板时,ons_list初始为undefined,直接访问ons_list.success会报错。可以用两种方式处理:
方式一:安全导航操作符
<li>{{ons_list?.success}}</li>
方式二:*ngIf判断
<ul *ngIf="ons_list"> <li>{{ons_list.success}}</li> </ul>
内容的提问来源于stack exchange,提问作者Ismail Yanık
相关产品推荐
相关产品推荐

