0
我有角2,如下面的方法服務:角2 HTTP服務返回不可變的數據問題
getEntityById = (id: number | string): Observable<Immutable.Iterable<any, any>> =>
this.http.get(`${this.baseUrl}/${id}`)
.map((response: Response) => Immutable.fromJS(this.helper.getResponseAsJson(response)))
.share();
我的目標如下:
- 返回數據的不可變版本所以用戶不能以影響其他訂戶的方式改變數據
- 只有在直接調用
getEntityById()
方法時才進行提取,而不是在訂閱時調用,因此使用share()
這是正常工作,但我不喜歡它返回一個基本類型的Immutable.Iterable<any, any>
(或<string, any>
爲此事)的事實。
我想要底層類型來表示我的實體的類型,所以更清楚什麼是返回給服務的消費者,它可以更好地執行。
有沒有更好的方法來編寫這個方法,所以它符合我上面描述的標準,但也指出了基礎類型?
UPDATE:
所以我改變了這個局面,返回我想要的類型,但似乎相當捲入這樣:
getEntityById = (id: number | string): Observable<MyEntity> => {
const subscription = this.http.get(`${this.baseUrl}/${id}`)
.map((response: Response) => Immutable.fromJS(this.helper.getResponseAsJson(response)))
.share()
.subscribe(result => {
this.entitySubject.next(result);
subscription.unsubscribe();
}, err => {
this.logger.error(this.helper.parseError(err));
this.entitySubject.error(err);
subscription.unsubscribe();
});
return this.entitySubject.map((immutable: Immutable.Iterable<any, any>) => immutable.toJS());
}
我覺得必須有實現更簡單的方法這個。
不確定我關注你。你是什麼意思只是返回'Immutable.fromJS(this.helper.getResponseAsJson(response)))'? – lintmouse
正確。 Map旨在遍歷一個集合並將這些值映射到其他東西(這就是爲什麼你得到一個Iterable後面)。如果你有一個輸入數組,只需調用.fromJS(),你就會得到一個'List',就像{Map}一樣。{} – rooftop
Map只是將輸入投影到任何你想要的。不一定是一個集合。 – lintmouse