【问题标题】:How to set a type for data received from Angular HTTP request?如何为从 Angular HTTP 请求接收的数据设置类型?
【发布时间】:2020-12-18 11:17:40
【问题描述】:

这是我获取数据的代码:

login() {
    const url = api + 'login';
    this.http.post(url, this.userModel)
      .subscribe(
        data => {
          localStorage.token = data.token;
          this.router.navigate(['/home']);
        },
        error => {
          alert(error.error.error);
        }
      )
  }

这将返回一个 JSON 格式

{
   message: "logged In Successful!",
   token: "e4affa4633fb046333731ae6fadcb980b98636b513a0fb80721759267b4efa5c9b7845663f2b1288"
}

它有效,它保存到本地存储,但这个错误一直在我的控制台中弹出?为什么?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您收到错误是因为 typescript 无法解析响应对象的类型,因此您需要指定发布请求的响应对象类型:

      login() {
        const url = api + 'login';
        this.http.post<{ message: string, token: string }>(url, this.userModel)
          .subscribe(
            data => {
              localStorage.token = data.token;
              this.router.navigate(['/home']);
            },
            error => {
              alert(error.error.error);
            }
          )
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多