簡體   English   中英

Angular / RxJs無法識別數組

[英]Angular/RxJs not recognising array

我不明白為什么下面的代碼無法按預期工作。

    public GetX(): Observable<MyDataType> {
    return this.http.get('http://localhost:64113/api/endpoint')
        .map((r: Response) => r.json())
        .map((r) => r.someProperty)
        .catch(error => Observable.throw(error));
}

問題是,即使我從.Net Core WebAPI端點返回一個數組,第二個映射函數也只會被調用一次。 看起來像:

[{}, {}, {}, {}...]

難道不應該對從服務器傳回的數組中的每個元素進行迭代映射嗎?

以下是console.log的結果

(124) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object…]

問題是您正在調用的第二個map函數。 Map將轉換應用於數據流,並應返回轉換后的元素。

當前,第二個映射使用webapi返回的POJO數組,但不會將它們再次傳遞回流流。

假設MyDataType是一個打字稿接口,並且包含從webapi返回的JSON對象的匹配屬性,則可以使用以下命令打印服務器響應:

return this.http.get('http://localhost:64113/api/endpoint')
        .map(r => r.json())
        .do(r => console.log(r))
        .catch(error => Observable.throw(error));

更新:如果要映射數組中每個元素的屬性,則應使用mergeMap

 return this.http.get('http://localhost:64113/api/endpoint')
            .map(r => r.json()) // map to json body
            .mergeMap(r => r) // flatten array
            .map(e => e.property) //map singular objects to a property
            .catch(error => Observable.throw(error));

MergeMap將通過將每個奇異POJO映射到其屬性之一來展平數組。 在這種情況下,函數的返回類型將變得非常准確。

您可以在此處找到有關操作員的更多信息

如果需要遍歷由ajax調用返回的數組,則應將其包裝在Observable.from函數中。 您確實需要在json之后的另一張地圖,該地圖不返回值,但是是可觀察的。 在這種情況下,請使用flatMap。

//code omitted for brevity
.map( r : Response => r.json() )
.flatMap((obj: any) => Observable.from(obj) )

此后,數組的Observablel變為單個值的Observable。 但是我對您提供的類型一無所知,並且無法查看該類型是否是數組的包裝器

我想從數組的每個元素中獲取一個屬性,然后返回這些屬性的數組。 例如[{property:1}, {property:2}, {}, {}...]

然后,我建議您像下面這樣,在數組上使用map,並使用Object.assign將想要的屬性分配給新對象

public GetX(): Observable<MyDataType> {
  return this.http.get('http://localhost:64113/api/endpoint')
    .map((r: Response) => r.json().map((x:any) => Object.assign({propertyName: x.property})))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM