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);
}
添加回答
举报