QuestionOne
QuestionOne

Reputation: 23

Retrieve data from json with multiple arrays?

I am having difficulties retrieving data from .json file in this format, I have tried headers, changing URL but it is not working:

{
    "cars": ["BMW", "Mercedes", "Fiat"],
    "testDrives": [
        {
            "start": "2020-02-03T11:00:00.000Z",
            "end": "2020-02-03T16:00:00.000Z",
            "name": "Bmw"
        },
        {
            "start": "2020-02-03T09:00:00.000Z",
            "end": "2020-02-03T12:30:00.000Z",
            "name": "Mercedes"
        }
  ]
}

My code:

 data = '../../assets/test.json';

  constructor(private http: HttpClient) { }

  getData() {
    this.http.get(this.data).subscribe(data => {
      console.log(data);
    });
  }

I keep getting this error: error

Upvotes: 0

Views: 47

Answers (1)

vinodaw
vinodaw

Reputation: 127

You need to define an interface with required properties to specify the response type

export interface ResponseModel{
  cars: string;
  testDrives: string;
}

and specify Response type in subscribe

getData() {
  this.http.get(this.data).subscribe((data: ResponseModel) => {
   console.log(data);
  });
 }

Upvotes: 1

Related Questions