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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…