angular - 无法访问 http 响应对象的属性
问题描述
有以下共享
export class DataStorageService {
constructor(private http: HttpClient) {}
fetchAll(dataType: string) {
let apiEndpoint = environment.config.urlLogin + '/api/' + dataType;
return this.http.get(apiEndpoint);
}
并在这里使用它
export class InvoiceListComponent implements OnInit {
invoices: Invoice[] = [];
constructor(private ds: DataStorageService) {
}
ngOnInit(): void {
this.fetchInvoices();
}
fetchInvoices() {
this.ds.fetchAll('invoices').subscribe((responseData) => {
if (responseData.hasOwnProperty('hydra:member')) {
//reaching here
// but this throws compile error
this.invoices = responseData['hydra:member'];
}
})
}
Angular 12 出现以下编译错误:
元素隐含地具有“任何”类型,因为类型“hydra:member”的表达式不能用于索引类型“对象”。“对象”类型上不存在属性“hydra:member”。
老实说,我完全不明白为什么会出现这种情况。我的意思是我什至可以肯定地检查这个属性是否存在?
解决方案
轻松修复!声明一个接口,指定您期望获得的数据类型:
// interface.ts
export interface MyType {
"hydra:member": string
}
将此类型分配给返回的数据:
// service
import { MyType } from './interface.ts';
...
return this.http.get(apiEndpoint) as Observable<MyType>;
如果我没有忘记任何事情,我认为这应该可以工作!
推荐阅读
- php - PHP CurRL - 由于 SSL 的空响应
- java - 使用 JDBC 从 PL/SQL 存储函数中获取表返回值
- reactjs - 组合减速器的相同动作类型
- package-managers - apt --fix-broken install 不起作用,安装 wine-stable 后包管理器损坏
- ubuntu - 如何构建 glibc 包的数学库?
- google-maps - 在谷歌地图javascript上单击POI时获取纬度和经度
- bit-manipulation - 如何强制 xor 操作保持在可见的 ascii 范围内?
- javascript - 在 Node 和 Google Sheets v.4 中同时批量更新单元格值和背景颜色
- javascript - 谷歌表格突出显示每行脚本中的最低数字
- javascript - 如何将相同的产品添加到带柜台的购物车中?