【问题标题】:Linq First equivalent to TypsScript+rxjsLinq First 等价于 TypeScript+rxjs
【发布时间】:2017-02-14 19:33:22
【问题描述】:

我熟悉 C# Linq,但对 ng2+TypeScript+rxjs 开发不熟悉。

在下面代码的getDetailByDetailId方法中,如何从可观察列表中获取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 方法给出以下两个错误。

错误:(47, 16) TS2322:类型“Observable”不可分配给类型“Observable”。类型 'Detail[]' 不可分配给类型 'Detail'。 “Detail[]”类型中缺少属性“DetailId”。

错误:(48, 45) TS2339: 类型“Detail[]”上不存在属性“DetailId”。

【问题讨论】:

    标签: angular typescript rxjs observable


    【解决方案1】:

    问题是getDetails 返回一个Observable&lt;Detail[]&gt;。所以发送到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);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-04
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多