Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

handling 400 and 401 status in angular

I am trying to implement login function. I am getting data using API. here is my 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);
  }
}

here is my 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");
        }
      });
   
  
    } 
  }

}

Below is postman result when I entered correct credentials.

"email": "[email protected]", "tokens": "{'refresh': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYxMzAxNTI5NSwianRpIjoiMzliNzY0N2ExMjVhNDI2M2E2MTVlYjhiZmQ4ZTgyYzgiLCJlbWFpbCI6InRlc3RAZ21haWwuY29tIn0.-mEy9rWyRm7lXsnG-JfoGFgn4GrLrOa-hAkBm0gyb8s', 'access': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjExODE3Njk1LCJqdGkiOiIwMTExNmU2NWI0OTM0YTcwYmJiNGM2ZjhkZDEyZTU4YSIsImVtYWlsIjoidGVzdEBnbWFpbC5jb20ifQ.Raf38'}" }

This is postman result when I entered incorrect credentials.

{ "detail": "Invalid credentials, try again" }

If I give correct credentials it is work fine.I want to know how I can handle 400 and 401.

question from:https://stackoverflow.com/questions/65931022/handling-400-and-401-status-in-angular

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Handling 400 or 401 is quite ambiguous you can do a lot of different things like trigger an action, you may show a message to the user or maybe use alerts as you did, This can help:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...