在 angular 中处理 400 和 401 状态
handling 400 and 401 status in angular
我正在尝试实现登录功能。我正在使用 API 获取数据。这是我的 authservice.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthserviceService {
constructor(private http:HttpClient) { }
login(data):Observable<any>{
console.log("I am server");
return this.http.post('http://localhost:8000/api/login/',data);
}
}
这是我的 loginComponent.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AuthserviceService } from 'src/app/authservice.service';
import { Router } from '@angular/router';
@Component({
selector: 'sl8-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
formGroup : FormGroup;
constructor(private authService :AuthserviceService,private _router : Router) { }
ngOnInit(): void {
this.initForm();
}
initForm(){
this.formGroup =new FormGroup({
email : new FormControl('',[Validators.required]),
password : new FormControl('',[Validators.required]),
})
}
loginProcess(){
if(this.formGroup.valid){
this.authService.login(this.formGroup.value).subscribe(results => {
if(results.tokens){
console.log(results);
alert("test");
}else{
alert("Invalid credentials, try again");
}
});
}
}
}
以下是我输入正确凭据后的邮递员结果。
"email": "test@gmail.com",
"tokens": "{'refresh': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYxMzAxNTI5NSwianRpIjoiMzliNzY0N2ExMjVhNDI2M2E2MTVlYjhiZmQ4ZTgyYzgiLCJlbWFpbCI6InRlc3RAZ21haWwuY29tIn0.-mEy9rWyRm7lXsnG-JfoGFgn4GrLrOa-hAkBm0gyb8s', 'access': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjExODE3Njk1LCJqdGkiOiIwMTExNmU2NWI0OTM0YTcwYmJiNGM2ZjhkZDEyZTU4YSIsImVtYWlsIjoidGVzdEBnbWFpbC5jb20ifQ.Raf38'}"
}
这是我输入错误凭据时邮递员的结果。
{
"detail": "Invalid credentials, try again"
}
如果我提供正确的凭据,它就可以工作fine.I想知道我如何处理 400 和 401。
处理 400 或 401 是很不明确的,你可以做很多不同的事情,比如触发一个动作,你可以向用户显示一条消息,或者像你一样使用警报,这可以帮助:
loginProcess(){
if(this.formGroup.valid){
this.authService.login(this.formGroup.value).subscribe(results => {
console.log(results);
alert("test");
// import HttpErrorResponse from @angular/common/http
}, (error: HttpErrorResponse) => {
// You can do anything with the error it is found in the error.error object.
const message = error.error.detail;
console.log(message);
if (error.status === 400)
alert('Invalid form inputs')
else if (error.status === 401)
alert('Invalid Credentials Provided')
});
}
添加更多内容以回答 Divin
loginProcess(){
const othis = this;
if(this.formGroup.valid) {
this.authService.login(this.formGroup.value).subscribe(results => {
console.log(results);
alert("test");
}, (error: HttpErrorResponse) => {
// do specific task related to this call only.
othis._utilityService.checkErrors(error);
});
}
在 UtilityService 中我会写一个方法 checkErrors
checkErrors(error: HttpErrorResponse) {
const message = error.error.detail;
// Show error message as popup or toast as notification
if (error.status === 400)
alert('Invalid form inputs')
else if (error.status === 401)
alert('Invalid Credentials Provided')
//Handle some more status here
}
通过这样做,您可以处理每个 API 调用的错误。不用到处写冗余代码
我正在尝试实现登录功能。我正在使用 API 获取数据。这是我的 authservice.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthserviceService {
constructor(private http:HttpClient) { }
login(data):Observable<any>{
console.log("I am server");
return this.http.post('http://localhost:8000/api/login/',data);
}
}
这是我的 loginComponent.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AuthserviceService } from 'src/app/authservice.service';
import { Router } from '@angular/router';
@Component({
selector: 'sl8-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
formGroup : FormGroup;
constructor(private authService :AuthserviceService,private _router : Router) { }
ngOnInit(): void {
this.initForm();
}
initForm(){
this.formGroup =new FormGroup({
email : new FormControl('',[Validators.required]),
password : new FormControl('',[Validators.required]),
})
}
loginProcess(){
if(this.formGroup.valid){
this.authService.login(this.formGroup.value).subscribe(results => {
if(results.tokens){
console.log(results);
alert("test");
}else{
alert("Invalid credentials, try again");
}
});
}
}
}
以下是我输入正确凭据后的邮递员结果。
"email": "test@gmail.com", "tokens": "{'refresh': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYxMzAxNTI5NSwianRpIjoiMzliNzY0N2ExMjVhNDI2M2E2MTVlYjhiZmQ4ZTgyYzgiLCJlbWFpbCI6InRlc3RAZ21haWwuY29tIn0.-mEy9rWyRm7lXsnG-JfoGFgn4GrLrOa-hAkBm0gyb8s', 'access': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjExODE3Njk1LCJqdGkiOiIwMTExNmU2NWI0OTM0YTcwYmJiNGM2ZjhkZDEyZTU4YSIsImVtYWlsIjoidGVzdEBnbWFpbC5jb20ifQ.Raf38'}" }
这是我输入错误凭据时邮递员的结果。
{ "detail": "Invalid credentials, try again" }
如果我提供正确的凭据,它就可以工作fine.I想知道我如何处理 400 和 401。
处理 400 或 401 是很不明确的,你可以做很多不同的事情,比如触发一个动作,你可以向用户显示一条消息,或者像你一样使用警报,这可以帮助:
loginProcess(){
if(this.formGroup.valid){
this.authService.login(this.formGroup.value).subscribe(results => {
console.log(results);
alert("test");
// import HttpErrorResponse from @angular/common/http
}, (error: HttpErrorResponse) => {
// You can do anything with the error it is found in the error.error object.
const message = error.error.detail;
console.log(message);
if (error.status === 400)
alert('Invalid form inputs')
else if (error.status === 401)
alert('Invalid Credentials Provided')
});
}
添加更多内容以回答 Divin
loginProcess(){
const othis = this;
if(this.formGroup.valid) {
this.authService.login(this.formGroup.value).subscribe(results => {
console.log(results);
alert("test");
}, (error: HttpErrorResponse) => {
// do specific task related to this call only.
othis._utilityService.checkErrors(error);
});
}
在 UtilityService 中我会写一个方法 checkErrors
checkErrors(error: HttpErrorResponse) {
const message = error.error.detail;
// Show error message as popup or toast as notification
if (error.status === 400)
alert('Invalid form inputs')
else if (error.status === 401)
alert('Invalid Credentials Provided')
//Handle some more status here
}
通过这样做,您可以处理每个 API 调用的错误。不用到处写冗余代码