1

the data of api is array but the response i am getting from it is as an object using following method

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-shipment',
  templateUrl: './shipment.component.html',
  styleUrls: ['./shipment.component.css'],
})
export class ShipmentComponent implements OnInit {
  li: any;
  shipment = [];
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('http://localhost:3000/shipments').subscribe((response) => {
      this.li = response;
    });
  }
  getShipments(): void {
    console.log(this.li);
  }
}
Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74
tdashby 87
  • 45
  • 5

1 Answers1

2

By default, the type returned by an http get request is Observable<Object> so you have to tell typescript that you expect an array. This can be simply done by typecating

  ngOnInit(): void {
    this.http.get<any[]>('http://localhost:3000/shipments').subscribe((response) => {
      this.li = response;
    });
  }

OR

  import { tap, map } from 'rxjs/operators';

  ngOnInit(): void {
    this.http.get('http://localhost:3000/shipments')
      .pipe(
         tap(console.log),
         map(x => x as any[])
       )
      .subscribe((response) => {
         this.li = response;
       });
  }

the line tap(console.log), is just for debugging to view the object returned from your api call

Owen Kelvin
  • 14,054
  • 10
  • 41
  • 74
  • Can you please provide insight to ... Found one library(exceljs) which supports this...https://stackoverflow.com/questions/67130632/how-to-export-dropdown-listwith-options-from-json-to-excel-in-angular-8/67157538#67157538 – Bravo Apr 21 '21 at 23:12