1 回答

TA貢獻1858條經驗 獲得超8個贊
那里有幾個問題。
錯誤消息是因為您使用的是
<T[]>
onget
和toPromise
,它們不是通用函數。只需在處理程序中應用類型T
即可。result
then
您正在陷入承諾創建反模式。您已經有一個承諾(來自
this.httpClient
),因此您不需要new Promise
.您正在為
new Promise
回調使用傳統函數,但隨后this
在其中使用,就好像它仍在引用您的類實例一樣。如果你要保留new Promise
,你會想要一個箭頭函數,所以它關閉了this
。
相反(見***
評論):
protected scroll<T>(path: string, pageSize: number, filter: string, data: T[]): Promise<T[]> {
// *** Return the result of calling `then` on the promise from `toPromise`
return this.httpClient
// *** Don't use <T[]> on `get` and `toPromise`
.get(this.appConfigService.buildApiUrl(path), { params })
.toPromise()
.then((result: T) => { // *** <== Note the `T`
// *** If it's really possible that `result` will be falsy and you don't want that
// to be valid, you can do this:
if (!result) {
throw new Error("appropriate error here");
}
return data.concat(result);
});
}
在操場上
更新:
我不應該從示例中刪除 if 條件:
沒關系,把上面的body放入ifblock即可:
protected scroll<T>(path: string, pageSize: number, filter: string, data: T[]): Promise<T[]> {
if (!filter) {
const params = new HttpParams()
.set('searchText', '')
.set('skip', data.length.toString())
.set('take', pageSize.toString());
return this.httpClient
// *** Don't use <T[]> on `get` and `toPromise`
.get(this.appConfigService.buildApiUrl(path), { params })
.toPromise()
.then((result: T) => { // *** <== Note the `T`
// *** If it's really possible that `result` will be falsy and you don't want that
// to be valid, you can do this:
if (!result) {
throw new Error("appropriate error here");
}
return data.concat(result);
});
}
return this.filter<T>(data, pageSize, filter, path);
}
添加回答
舉報