【发布时间】:2020-11-04 12:19:32
【问题描述】:
对不起,我是前端开发的新手
我已经在 Angular 上进行了系统登录,但如果令牌未能获取或获取 HttpErrorResponse,我的系统登录不会返回错误消息
我想向用户显示错误消息作为错误的密码/用户名
这是我的 API 中没有用户名和密码时的响应
api.service.ts
baseUrlAuth = 'http://localhost:8000/api/auth/token/login/'
auth.component.ts
interface TokenObj {
auth_token: string;
}
authForm = new FormGroup({
username: new FormControl(''),
password: new FormControl(''),
rememberMe : new FormControl(''),
});
headers = new HttpHeaders({
'Content-Type': 'application/json',
});
loginUser(authData) {
let body = JSON.stringify(authData);
return this.httpClient.post(this.ApiService.baseUrlAuth, body, {
headers: this.headers
},);
}
saveForm() {
this.loginUser(this.authForm.value).subscribe(
(result: TokenObj) => {
if (this.authForm.value.rememberMe == true) {
this.cookieService.set('userToken', result.auth_token)
}
sessionStorage.setItem('userSession', result.auth_token);
window.location.href = '/home';}
);
}
auth.component.html
<div class="container">
<div class="row">
<div class="col col-8 col-sm-8 col-lg-6 mx-auto my-auto">
<form [formGroup]="authForm" (ngSubmit)="saveForm()">
<div class="form-group">
<label for="username">Username</label>
<input type="email" class="form-control" id="username" placeholder="Enter Username" required
formControlName="username">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone
else.</small>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password"
formControlName="password" required>
</div>
<div class="form-check">
<input type="checkbox" formControlName="rememberMe" id="rememberMe" class="form-check-input">
<label for="rememberMe" class="form-check-label">Remember Me</label>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary" style="width: 250px;">Login</button>
</div>
<div class="text-center sign-up">
<p>Not a Member</p>
<a href="">Sign Up Now</a>
</div>
</form>
</div>
</div>
</div>
【问题讨论】:
-
在
subscribe之后next()之后还有另一种方法可以捕获错误 -
我可以在这里找到documentation吗?
-
你可以参考这个angular.io/guide/observables
标签: angular api rest authentication token