I'm using angular and Laravel for user authentication followed this link :
https://www.positronx.io/laravel-jwt-authentication-tutorial-user-login-signup-api/ https://www.positronx.io/laravel-angular-token-based-authentication-with-jwt/
Authentication is working, this is login function :
onSubmit() {
this.authService.signin(this.loginForm.value).subscribe(
(result: any) => {
this.responseHandler(result);
},
error => {
this.errors = error.error;
if(this.errors.error_message)
{
this.toastr.error('', this.errors.error_message);
}
// }
},() => {
this.authState.setAuthState(true);
this.loginForm.reset()
this.router.navigate(['user/dashboard']);
this.toastr.success('Success', 'Logged In Successfully');
}
);
}
// Handle response
responseHandler(data :any ){
this.token.handleData(data.access_token);
}
}
issue is when 401 is returned from the server then also it is executing this success block :
this.authState.setAuthState(true);
this.loginForm.reset()
this.router.navigate(['user/dashboard']);
this.toastr.success('Success', 'Logged In Successfully');
In laravel i'm returning 401 :
if (! $token = auth()->attempt($validator->validated())) {
return response()->json(['status'=>true,'error_message' => 'Invalid Credentials'], 401);
}
That's not success block. A subscribe takes 3 arguments.
1.Next
2.Error
3.Complete
No matter what happens to your observable(success or error), if you write a complete method it always will be called. so in order to prevent this, put those 4 lines in Next method
this.authService.signin(this.loginForm.value).subscribe(
(result: any) => {
this.responseHandler(result);
this.authState.setAuthState(true);
this.loginForm.reset()
this.toastr.success('Success', 'Logged In Successfully');
this.router.navigate(['user/dashboard']);
},
error => {
this.errors = error.error;
if(this.errors.error_message){
this.toastr.error('', this.errors.error_message);
}
});