2017-06-06 40 views
-2

我已閱讀了大部分與此類似的問題,但仍然不明白如何在我的應用中使.find()工作。Angular 4 - 如何正確使用.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": "" 
    }] 
} 

所以,我在這裏做的是:通過descriptionFormGroup - vehicleDescription字段至searchByVehicleId方法。在這裏我想找到id通過vehicleDescription velue(它是API2中的"description"字段)。當我們找到id時,我們用它進一步在this.vehicleService.getVehicleByVehicleId ...

主要問題是 - 我不知道,如何正確實施.find()

由於

+1

https://stackoverflow.com/a/35398031/4826457 –

+0

解決:'this.searchVehicleId = this.description.find(X => X。 id === x.id).id.toString();'。感謝您的幫助,如果我之前發現了這個問題,我的身邊就沒有問題了。 – Haseoh

回答

1

MDN docs的:

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