LBA
LBA

Reputation: 4089

Cannot access property of http response object

Having the following shared

export class DataStorageService {

  constructor(private http: HttpClient) {}

  fetchAll(dataType: string) {
    let apiEndpoint = environment.config.urlLogin + '/api/' + dataType;

    return this.http.get(apiEndpoint);
  }

and using it here

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'];
      }

    })
  }

I get the following compile error with Angular 12:

Element implicitly has an 'any' type because expression of type '"hydra:member"' can't be used to index type 'Object'. Property 'hydra:member' does not exist on type 'Object'.

Honestly I do not understand at all why this is showing up. I mean I even reach the positive check whether this property exists?

Upvotes: 0

Views: 1193

Answers (1)

mike
mike

Reputation: 1863

Easy fix! Declare an interface specifying the type of data you are expecting to get:

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

assign this type to the returned data:

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

I think this should work if I did not forget anything!

Upvotes: 2

Related Questions