2016-10-06 8 views
1

私はC#Linqに精通していますが、ng2 + TypeScript + rxjs開発では初めてです。Linq TypsScript + rxjsに最初に相当

以下のコードの方法では、Firstと一致する項目を監視対象リストから取得する方法はありますか。

モデル

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

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

方法

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方法は、2つのエラーを次与えます。

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[]'.

答えて

3

問題がgetDetailsObservable<Detail[]>を返すということです。したがって、firstメソッドに放出される値は、Detailではなく、Detail[]です。あなたができることは、最初にflatMapで配列を平坦化してからfirst

getDetailByDetailId(masterId: string, detailId: string): Observable<Detail> { 
    return this.getDetails(masterId) 
    .flatMap(details => details) 
    .first((d: Detail) => d.DetailId === detailId); 
} 
関連する問題