繁体   English   中英

angular2 TS2322类型&#39;Promise <void> &#39;不可分配给&#39;Promise <string> &#39;当给定字符串时

[英]angular2 TS2322 Type 'Promise<void>' is not assignable to type 'Promise<string>' when given a string

使用Angular 2,我有一个处理我的API调用的服务。 在服务中,我有一个handleError函数,该函数为错误消息返回Promise<string> 我正在尝试向handleError添加一些功能,如果存在凭据错误,该功能将在以后将页面重定向到登录屏幕。 当我这样做时,即使我返回相同的Promise,然后尝试从中删除链条,TypeScript也会引发TS2322错误。

错误TS2322:类型'Promise <void>'无法分配给类型'Promise <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对您大吼大叫,因为appState.refreshredirects.loginalerts.warning返回空值。 为了正确地链接它,请使用链接设置一个变量,然后返回该变量:

    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;

值得一提的是,因为您的Promise被拒绝,所以不会调用then

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM