【问题标题】:Angular: Can you extract status of text responseType?Angular:你能提取文本响应类型的状态吗?
【发布时间】:2019-08-17 02:49:24
【问题描述】:

我有一个使用 Spring Boot 创建的服务器项目,它返回带有字符串的 ResponseEntity 以发布请求。我希望我的角度应用程序根据响应状态做出反应。

this.httpClient.post(
    'http://localhost:8080/users',
    {
        "username": username,
        "email": email,
        "password": password
    },
    {
        observe: 'response'
    })
.subscribe(response => {
    if (response.status === 200) {
        alert('Hello!');
    }
 });

但是使用上面的代码,我收到一个错误记录到控制台通知:

"Http failure during parsing for http://localhost:8080/users"
(status is 200 as expected but alert does not work).

我知道我可以把post的第三个参数改成

{responseType: 'text'}

并摆脱错误,但是我不知道要获取此类响应的状态代码。

有办法吗?

【问题讨论】:

  • 您可以在服务器上设置响应对象的状态。
  • 正如你所说的,{responseType: 'text'} 会告诉 Angular 不要期望 JSON 响应。并且由于您已经传递了observe: response,您将在订阅中获得完整的 http 响应对象(包括标头)。使用它你可以检查状态码。
  • @RomanC - 在服务器上设置状态
  • @ashish.gd - 不幸的是,正如我所提到的 - 代码包括观察帖子中可见的消息文本有错误,警告“你好!”甚至不显示

标签: javascript angular spring-boot


【解决方案1】:

subscribe 的第一个回调被称为 next 回调,只要 observable 发出一个值就会调用它。如果出现错误,则调用error 回调,它可以作为第二个参数提供给subscribe(还有其他替代方案)。 not 使用 responseType: 'text' 时您没有看到 alert 触发的原因是,当出现错误时未调用您提供的回调函数。

正如我已经建议的那样,一种选择是提供错误回调。这是一个例子:

this.httpClient.post(
    'http://localhost:8080/users',
    { username, email, password },
    { observe: 'response' })
.subscribe(
    response => {
        // Only called for success.
        ...
    },
    errorResponse => {
        // Called when there's an error (e.g. parsing failure).
        if (errorResponse.status === 200) {
            alert('Hello (for real this time)!');
        }
    });

在这里重新阅读原始问题后,我认为您真正的问题可能只是您没有结合responseType: 'text'observe: 'response'。这就是它的样子:

this.httpClient.post(
    'http://localhost:8080/users',
    { username, email, password },
    { observe: 'response', responseType: 'text' })
.subscribe(response => {
    if (response.status === 200) {
        alert('Hello!');
    }
});

【讨论】:

    【解决方案2】:
    if (parseInt(response.status) === 200)
    

    由于response.status 是字符串,因此您无法使用 === 运算符进行检查,因为它会同时检查类型和值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 2010-09-23
      • 2014-01-08
      • 1970-01-01
      相关资源
      最近更新 更多