0

I am making an app in ionic 3 and I am trying to fetch data from an url.

This is my code in data.ts and my data provider:

   getVehicleStatus() {
    return this.http.get<VehicleStatus>(this.url);
  }

This is my vehicle class:

class VehicleStatus {
    status: string;
    plate: string;
    code: string;
    message: string;
}

I am calling the method into my home.ts file.

  ionViewDidLoad() {
    console.log(this.getStatus('test3'));
  }

  getStatus(plate: string) {
    this.dataService.getVehicleStatus()
      .subscribe((data: VehicleStatus) => this.vehiclestatus = [{ ...data }]);
  }

To test out if everything works I hard code a license plate number to log it into my chrome developer tools. It said 'Undefined'.

This is how the json data looks like:

[{"status":"P","plate":"test2","code:"MGP150151","message":"fail"}
,{"status":"P","plate":"test3","code":"MGP160298","message":"fail"}
,{"status":"P","plate":"test4","code":"MGP140085","message":"succes"}
,{"status":"O","plate":"test5","code":"MGP150175","message":"succes"}]

I should get this object back:

{"status":"P","plate":"test3","code":"MGP160298","message":"fail"}

But it doesn't work and got the message undefined.

I have used the following source:

https://angular.io/guide/http

How can I search in the array and bind it to my HTML page in ionic 3?.

Can someone point me in the right direction?.

Kind regards .

Fearcoder
  • 753
  • 3
  • 15
  • 47

2 Answers2

0

You need array.find to get the matching value, which will return the first matching element from the array

 this.vehiclestatus =  data.find(vehicle=>vehicle.plate === plate);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

The responsibility to find the VehicleStatus from the list should be of the service rather than of the Component itself.

Consider changing your Service Implementation to take up that responsibility. You can use the map operator to transform the response to return the VehicleStatus found based on the plate that will be passed as an arg while calling the getVehicleStatus method.

import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

getVehicleStatus(plate): Observable<VehicleStatus> {
  return this.http.get<VehicleStatus[]>(this.url)
    .pipe(
      map(statuses => statuses.find(status => status.plate === plate))
    );
}

Then in your home.ts:

ionViewDidLoad() {
  this.getStatus('test3');
}

getStatus(plate: string) {
  this.dataService.getVehicleStatus(plate)
    .subscribe((data: VehicleStatus) => this.vehiclestatus = data);
}
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110