Angular 4 - 如何正确使用.find()?

时间:2017-06-06 08:33:39

标签: angular typescript

我已经阅读了与此相似的大部分问题,但我仍然不了解如何在我的应用中使.find()工作。

我有API服务:

export class VehicleService {
  private defUrl = 'API';

  constructor(private http: Http) { }

  getVehicleByVehicleId(vehicleid?: any) {
    const url = (!vehicleid) ? this.defUrl : 'API1&vehicle_id=' + vehicleid;
    return this.http.get(url)
      .map(res => res.json());
  }


    searchVehicleId(description?: string) {
    const url = (!description) ? this.defUrl : 'API2&description=' + description;
    return this.http.get(url)
      .map(res => res.json().vehicles);
  }
}

组件

export class VehicleComponent implements OnInit {

  ngOnInit() {

    this.searchQuery = new FormGroup({
      vehicleDescription: new FormControl('', Validators.required)
    });
  }


  constructor(private vehicleService: VehicleService) { }

  public fleet: Fleet[];
  public description: Description[];
  public searchQuery: FormGroup;
  public searchVehicleId: any;


  public searchByVehicleId(searchQuery) {
    this.vehicleService
      .searchVehicleId(searchQuery.value.vehicleDescription)
      .subscribe(searchQuery => {
        this.description = searchQuery;
        this.searchVehicleId = this.description.find() // <= HOW TO IMPLEMENT THIS?
    this.vehicleService
      .getVehicleByVehicleId(this.searchVehicleId)
      .subscribe(searchQuery => {
        this.vehicle = searchQuery;
      })
      });
  }
interface Vehicle {
  status: number;
  dallases: Vehicle[];
}

interface VehicleDetails {
  vehicle_id: number;
  dallassettings: string;
  dallasupdated: string;
  dallas_list: DallasList[];
}

interface DallasList {
  number: number;
  auth: number;
}

//////////////////////////////////
//////////////////////////////////

interface Description {
  vehicles: DescriptionDetails[];
}

interface DescriptionDetails {
  id: number;
  custom_description: string;
  description: string;
}

API2

{
    "vehicles": [{
        "description": "SKODA ROOMSTER",
        "id": 123456,
        "custom_description": ""
    }, {
        "description": "SKODA ROOMSTER",
        "id": 123456789,
        "custom_description": ""
    }]
}

所以,我在这里做的是:将description - FormGroup字段中的vehicleDescription传递给searchByVehicleId方法。在这里,我想找到id通过vehicleDescription velue {它在API2中的"description"字段中的id。当我们找到this.vehicleService.getVehicleByVehicleId时,我们会在.find() ...

中进一步使用它

主要问题是 - 我不知道如何正确实施{{1}}。

由于

1 个答案:

答案 0 :(得分:2)

MDN docs

this.searchVehicleId = this.description.find(x => x.id === someId);