[英]angular2 TS2322 Type 'Promise<void>' is not assignable to type 'Promise<string>' when given a string
Using Angular 2, I have a service that handles my API calls. 使用Angular 2,我有一个处理我的API调用的服务。 In the service, I have a handleError function that returns a
Promise<string>
for the error message. 在服务中,我有一个handleError函数,该函数为错误消息返回
Promise<string>
。 I'm trying to add some functionality to the handleError that will redirect the page afterwards to the login screen if there are credential errors. 我正在尝试向handleError添加一些功能,如果存在凭据错误,该功能将在以后将页面重定向到登录屏幕。 When I do that, TypeScript throws a TS2322 error even though I'm returning the same Promise and then trying to do some chains off of it.
当我这样做时,即使我返回相同的Promise,然后尝试从中删除链条,TypeScript也会引发TS2322错误。
error TS2322: Type 'Promise<void>' is not assignable to type 'Promise<string>'.
错误TS2322:类型'Promise <void>'无法分配给类型'Promise <string>'。 Type 'void' is not assignable to type 'string'.
类型“ void”不可分配给类型“ string”。
private handleError(error: Error): Promise<string> {
let message = "Something went wrong loading data from the API.";
if (error.response.status === 0) {
message = "Unable to contact server. Please file a bug report.";
}
if (error.message) {
message = "API Service Error retrieving page: " + error.message;
}
this.alerts.error(message);
if (error.response.status === 403) {
if (error.message.indexOf("Authentication credentials") !== -1) {
return Promise.reject<string>(message) // this line errs with TS2322
.then(() => this.appState.refresh())
.then(() => this.redirects.login())
.then(() => this.alerts.warning("Redirected to login because no credentials found."));
} else {
this.redirects.index();
}
}
return Promise.reject<string>(message);
}
return Promise.reject<string>(message) // this line errs with TS2322
.then(() => this.appState.refresh())
.then(() => this.redirects.login())
.then(() => this.alerts.warning("Redirected to login because no credentials found."));
Typescript is yelling at you because appState.refresh
, redirects.login
, or alerts.warning
returns a void value. Typescript对您大吼大叫,因为
appState.refresh
, redirects.login
或alerts.warning
返回空值。 To chain it correctly, set a variable with the chains, then return the variable: 为了正确地链接它,请使用链接设置一个变量,然后返回该变量:
let result = Promise.reject<string>(message);
result.then(() => this.appState.refresh())
.then(() => this.redirects.login())
.then(() => this.alerts.warning("Redirected to login because no credentials found."));
return result;
It's worth mentioning also that none of the then
s will be called because your Promise rejected. 值得一提的是,因为您的Promise被拒绝,所以不会调用
then
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.