I am trying to build an application using the,
- Fastapi - Python as backend which exposes the API's.
- Angular - frontend and rxjs/Observables for subscribing to the API's using httpClient.
It works well if the response is success as expected.
But, whenever the Error occurs, the error is unable to captured as expected because the Error Object is undefined when I access it wheareas the response object has the value in network tab response section.
In my python code I have written a logic for login API as below:
@auth_router.post("/login", response_model=UserLoginResponse)
async def login(user_login: UserLogin, request: Request, db: Session = Depends(get_db)):
try:
user = db.query(User).filter(User.email == user_login.email).first()
if not user or not bcrypt.checkpw(user_login.password.encode('utf-8'), user.encrypted_password.encode('utf-8')):
print('')
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "..."},
)
access_token = create_access_token(data={"sub": user.email})
# Update user information
user.access_token = access_token
user.is_currently_logged_in = True
user.last_sign_in_at = user.current_sign_in_at
user.current_sign_in_at = datetime.datetime.now()
user.last_sign_in_ip = user.current_sign_in_ip
user.current_sign_in_ip = request.client.host
db.commit()
# Create a response object
response_model = {
'id':user.id,
'first_name':user.first_name,
'last_name':user.last_name,
'email':user.email,
'role':user.role,
}
response = JSONResponse(content=response_model)
response.headers["Authorization"] = f"Bearer {access_token}"
return response
except ValidationError as e:
raise HTTPException(status_code=422, detail=str(e))
In my angular application I have called the API in service as below:
.service.ts file in Angular Front-end:
public logIn(userCredentials: UserCredentials): Observable<HttpResponse<any>> {
return this.http
.post<LoginResponse>(`${this.apiUrl}/login`, userCredentials, {
observe: 'response',
})
.pipe(
map((httpResponse: HttpResponse<LoginResponse>) => {
const token = httpResponse.headers.get('authorization');
if (httpResponse.body && token) {
const userDetails: AuthenticationState = {
name: httpResponse.body.first_name,
email: httpResponse.body.email,
token: token,
};
this.store.dispatch(setLoggedInUser(userDetails));
}
return httpResponse;
})
);
}
component.ts file to subscribe for that Observable :
logIn(): void {
this.isLoading = true;
const observer = this.authService.logIn(this.loginForm.value).subscribe({
next: (loginResponse: HttpResponse<LoginResponse>) => {
this.router.navigateByUrl('/dashboard');
this.toastrService.success('Logged in successfully');
this.isLoading = false;
},
error: (error) => {
console.log('error...', error);
this.toastrService.error(error);
this.isLoading = false;
},
});
this.subscriptions.add(observer);
}
**NOTE : **
When I console the error it is undefined as below:
Also If check with the network tab response section it has the value as object as below if any error occurs ( Success response No Problem works fine ):