【发布时间】:2022-01-26 17:30:28
【问题描述】:
我有一个 Angular 9 项目,我在其中使用 HttpClient 通过 HTTP 帖子执行登录。
如果登录失败,则返回 HTTP 403 和 JSON 响应,其中包含要在 UI 上显示的错误消息。
我的问题是我的错误处理程序总是用一个简单的字符串Forbidden 调用,而不是我想要的响应正文。我怎样才能检索响应正文?它已正确返回到浏览器。
我有这样的事情:
import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' })
export class AccountService {
constructor(
private http: HttpClient,
// ...
)
login(userName, userPassword) {
return this.http.post(`login`, {user: userName, password: userPassword});
}
}
我有一个组件,它只是检索返回的错误并将其显示在 UI 上。
this.accountService.login(this.f.username.value, this.f.password.value)
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
error => {
// error is a string here
this.alertService.error(error.errorMessage);
this.loading = false;
});
【问题讨论】:
标签: angular typescript post