首页 > 解决方案 > 无法访问 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”。

老实说,我完全不明白为什么会出现这种情况。我的意思是我什至可以肯定地检查这个属性是否存在?

标签: angulartypescript

解决方案


轻松修复!声明一个接口,指定您期望获得的数据类型:

// interface.ts
export interface MyType {
    "hydra:member": string
}

将此类型分配给返回的数据:

// service
import { MyType } from './interface.ts';
...
return this.http.get(apiEndpoint) as Observable<MyType>;

如果我没有忘记任何事情,我认为这应该可以工作!


推荐阅读