2016-10-06 2 views
1

Ich bin vertraut mit C# Linq, aber neu in ng2 + TypeScript + rxjs Entwicklung.Linq Erste Entsprechung zu TypSScript + rxjs

In getDetailByDetailId Methode von unter Code, wie man First gefundenen Artikel aus beobachtbarer Liste?

Modelle

export class Master { 
    Id: string; 
    SomeProperty: string; 
    Details: Detail[]; 
}  

export class Detail { 
    DetailId: string; 
    DetailProperty: string; 
} 

Methoden

getMaster(id:string): Observable<Master>{ 
    return this.http.get(this.webUrl + "/" + id) // web api 
     .map(this.extractData) 
     .catch(this.handleError); 
} 

private extractData(res: Response) { 
    let body = res.json() as Master[]; 
    return body || []; 
} 

getDetails(masterId: string): Observable<Detail[]>{ 
    return this.getMaster(masterId) 
     .map(master => master.Details); 
} 

getDetailByDetailId(masterId: string, detailId: string): Observable<Detail>{ 
    return this.getDetails(masterId) 
     .first(d => d.DetailId === detailId); // <-- Error occurred 
} 

getDetailByDetailId Methode gibt zwei Fehler folgen.

Error:(47, 16) TS2322: Type 'Observable<Detail[]>' is not assignable to type 'Observable<Detail>'. Type 'Detail[]' is not assignable to type 'Detail'. Property 'DetailId ' is missing in type 'Detail[]'.

Error:(48, 45) TS2339: Property 'DetailId' does not exist on type 'Detail[]'.

Antwort

3

Das Problem ist, dass getDetails eine Observable<Detail[]> zurück. Der Wert, der an das first-Verfahren ausgegeben wird, ist also ein Detail[], kein einziger Detail. Was Sie tun können, ist das Array zunächst mit flatMap zu glätten, dann können Sie first

getDetailByDetailId(masterId: string, detailId: string): Observable<Detail> { 
    return this.getDetails(masterId) 
    .flatMap(details => details) 
    .first((d: Detail) => d.DetailId === detailId); 
} 
aufrufen