以角度处理 400 和 401 状态

问题描述

我正在尝试实现登录功能。我正在使用 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('',})
  }

  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",“标记”: “{ '刷新': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYxMzAxNTI5NSwianRpIjoiMzliNzY0N2ExMjVhNDI2M2E2MTVlYjhiZmQ4ZTgyYzgiLCJlbWFpbCI6InRlc3RAZ21haWwuY29tIn0.-mEy9rWyRm7lXsnG-JfoGFgn4GrLrOa-hAkBm0gyb8s', '接入': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjExODE3Njk1LCJqdGkiOiIwMTExNmU2NWI0OTM0YTcwYmJiNGM2ZjhkZDEyZTU4YSIsImVtYWlsIjoidGVzdEBnbWFpbC5jb20ifQ.Raf38'}” }

这是我输入错误凭据时的邮递员结果。

{ "detail": "无效凭据,重试" }

如果我提供正确的凭据,它就可以正常工作。我想知道如何处理 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 调用的错误。无需到处编写冗余代码。