在本地构建(ng build)我的项目时出现以下错误。它在本地主机上运行良好。
error TS2349: This expression is not callable.
No constituent of type 'PromiseSettledResult\<any\>' is callable at
results.forEach((result, index) =\>{...})
我的 checkImageUrl 方法的代码是这样的,我收到错误
async checkImageUrl(type) {
const myArray = type === 'new' ? this.newArray : this.oldArray;
const promises = myArray.map(item => {
if (!(item?.imageURL.includes('http'))) {
return this.getImage(item?.imageURL)
.then(imageBlob => {
const bolbImageUrl = URL.createObjectURL(imageBlob);
const safeImageUrl = this.sanitizer.bypassSecurityTrustResourceUrl(bolbImageUrl);
return safeImageUrl;
})
.catch(_error => Promise.resolve(item?.imageURL));
} else {
return Promise.resolve(item?.imageURL);
}
});
try {
const results: PromiseSettledResult<any>[] = await Promise.allSettled(promises);
// const results = await Promise.allSettled(promises) as PromiseSettledResult<MyPromiseResult>[];
results.forEach((result, index) => { // -------------> error at this line number
if (result.status === 'fulfilled' && result.value) {
myArray[index].imageURL = result.value;
}
});
} catch (_error) {
this.spinner.hide();
}}
我的 getImage 方法是:
我还尝试为此提供结果变量的类型:
getImage(docId): Promise<Blob> {
return new Promise((resolve, reject) => {
this.http.get(BaseUrl + '/'+docId, { responseType: 'blob', observe: 'response' })
.subscribe((response: HttpResponse<Blob>) => {
const blob = response.body;
resolve(blob);
}, error => {
reject(error);
});
});
}
const results: PromiseSettledResult\<MyPromiseResult\>\[\] = await Promise.allSettled(promises);
其中 myPromiseResult 被声明为:
type MyPromiseResult = SafeResourceUrl | string;
但仍然出现错误
错误表明结果变量(PromiseSettledResult)的类型不可调用。这意味着您不能对其使用 forEach 方法。 要修复此错误,您需要为结果数组中的每个元素提供类型。在您的情况下,您似乎想为每个元素分配 SafeResourceUrl 或字符串类型。为此,您可以使用如下联合类型:
const results: PromiseSettledResult<SafeResourceUrl | string>[] = await Promise.allSettled(promises);
这将确保结果数组中的每个元素都是 SafeResourceUrl 或字符串类型,这将允许您对其使用 forEach 方法。
此外,请确保您在 getImage 方法中正确声明了 results 变量的类型。它也应该是
PromiseSettledResult<SafeResourceUrl | string>[]
类型,因为您将相同的类型传递给 Promise.allSettled 方法。