Javascript 角度:可以提取文本响应类型的状态吗?

Javascript 角度:可以提取文本响应类型的状态吗?,javascript,angular,spring-boot,Javascript,Angular,Spring Boot,我有一个使用spring boot创建的服务器的项目,它返回ResponseEntity,并带有post请求的字符串。我希望我的角度应用程序根据响应状态做出反应 this.httpClient.post( 'http://localhost:8080/users', { "username": username, "email": email, "password": password }, { ob

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

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'}
并消除错误,但我不知道如何获得这种响应的状态代码

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

if (parseInt(response.status) === 200)

因为
response.status
是字符串,您不能使用===运算符进行检查,因为它同时检查类型和值。

subscribe
的第一个回调称为
next
回调,每当可观测对象发出值时调用该回调。如果出现错误,将调用
error
回调,该回调可以作为
subscribe
的第二个参数提供(还有其他替代方法)。当不使用
responseType:'text'
时,您没有看到您的
警报
触发的原因是,出现错误时没有调用您提供的回调函数

正如我已经建议的,一个选项是提供一个错误回调。下面是一个例子:

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)!');
        }
    });

在重新阅读这里的原始问题之后,我认为您真正的问题可能只是您没有将
响应类型:'text'
观察:'response'
组合在一起。下面是它的样子:

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

您可以在服务器上设置响应对象的状态。正如您正确地说的,
{responseType:'text'}
将告诉Angular,您不希望看到JSON响应。由于您已经在传递
observe:response
,您将在订阅中获得完整的http响应对象(包括头)。使用它可以检查状态代码。@RomanC-status设置为onserver@ashish.gd-不幸的是,正如我提到的-对于包含observe的代码,在post中可以看到消息文本时出现错误,用“Hello!”发出警报甚至没有显示