Using Angular 2, I have a service that handles my API calls. In the service, I have a handleError function that returns a Promise<string>
for the error message. 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. 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.
error TS2322: Type 'Promise<void>' is not assignable to type 'Promise<string>'. Type 'void' is not assignable to type '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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.