我需要在我的应用程序中交织 promise :
protected scroll<T>(path: string, pageSize: number, filter: string, data: T[]): Promise<T[]> {
let promise = new Promise<T[]>(function(resolve, reject) {
this.httpClient
.get<T[]>(this.appConfigService.buildApiUrl(path), { params })
.toPromise<T[]>()
.then(result => {
if (result) {
resolve(data.concat(result));
}
})
.catch(function(e) {
reject(e);
});
});
return promise;
}
我的问题是我收到以下消息: “无类型函数调用可能不接受类型参数”
我该如何解决这个问题?
更新:
我不应该从示例中删除 if 条件:
if (!filter) {
const params = new HttpParams()
.set('searchText', '')
.set('skip', data.length.toString())
.set('take', pageSize.toString());
const promise = new Promise<T[]>((resolve, reject) => {
this.httpClient
.get<T>(this.appConfigService.buildApiUrl(path), { params })
.toPromise<any>()
.then(result => {
if (result) {
resolve(data.concat(result));
}
resolve(data);
})
.catch(e => reject(e));
});
return promise;
}
// also returning a promise
return this.filter<T>(data, pageSize, filter, path);
最佳答案
这里存在一些问题。
错误消息是因为您正在使用
<T[]>
上get
和toPromise
,这不是通用函数。只需应用类型T
至result
在then
处理程序。您正在陷入 promise 创建反模式。您已经有一个 promise (来自
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);
});
}
<小时/>
UPDATE:
I should not have removed the if condition from the example:
没关系,把上面的body放入if
即可 block :
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);
}
关于javascript - Angular 使用 Promise 并在 Promise 中使用泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58554501/