'How to show "Login In failed.Please try again" message in angular when API returns the response?
I have simple login screen in Angular as:
When the username and password is entered, it successfully hits the /login URL and if it is correct it goes to the userdashboard or admindashboard and when username and password is incorrect it shows me /403 forbidden page.
The output in console comes like:
However I want to show "Login Failed Please enter correct Username and Password Message" but the API is returning the response in the form
@PostMapping(value="/login")
public ResponseEntity<UserDTO> login(@RequestBody User user,HttpServletRequest request,HttpServletResponse response){
try {
Authentication authentication= authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword()));
final JwtUser userDetails=(JwtUser) authentication.getPrincipal();
System.out.println(userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
final String token=jwtTokenUtil.generateToken(userDetails);
response.setHeader("Token",token);
return new ResponseEntity<UserDTO>(new UserDTO(userDetails.getUser(), token),HttpStatus.OK);
} catch(Exception e) {
throw new UnauthorizedExcpetion(e.getMessage());
}
}
If login is success it returns user object neither it returns the message "Bad Credentials".
And in my Angular I have tried to check the error condition and want to apply the message strategy but it is not printing in console.log() if the login is failed but if the login is success then response is printed in console.log().
loginUser(user:any){
this.userService.loginUser(user).subscribe((response) => {
console.log("test");
if (response) {
console.log(response.token);
if (response.token) {
localStorage.setItem('currentUser',JSON.stringify(response));
if(response.user.role==='ADMIN') {
this.router.navigate(['/admindashboard']);
} else {
this.router.navigate(['/userdashboard']);
}
} else {
console.log(response.error.message);
}
}
})
}
userservice.ts
loginUser(user:any):Observable<any>{
const headers=new HttpHeaders({'Access-Control-Allow-Origin':'*'});
return this.http.post("http://localhost:8080/login",user,{headers:headers});
}
Solution 1:[1]
The response that you are getting goes into the error block in the front end so declare a boolean variable as showErrormessage as false and write the following code in HTML:
<div *ngIf="showErrorMessage">
<h1>Invalid username and password Please try again</h1>
</div>
And in ts file write this
//Declare this variable
showErrorMessage=false;
loginUser(user:any){
showErrorMessage = false;
this.userService.loginUser(user).subscribe(
(response) => {
console.log("test");
if (response) {
console.log(response.token);
if (response.token) {
localStorage.setItem('currentUser', JSON.stringify(response));
if (response.user.role === 'ADMIN') {
this.router.navigate(['/admindashboard']);
} else {
this.router.navigate(['/userdashboard']);
}
} else {
console.log("No Token");
}
}
},
(error) => {
showErrorMessage = true;
}
)
}
Solution 2:[2]
In this case, you will get your response in the error function of observable. So, just catch the error.
Here I have updated the code.
loginUser(user:any){
this.userService.loginUser(user).subscribe((response) => {
console.log("test");
if(response){
console.log(response.token);
if(response.token){
localStorage.setItem('currentUser',JSON.stringify(response));
if(response.user.role==='ADMIN'){
this.router.navigate(['/admindashboard']);
}else{
this.router.navigate(['/userdashboard']);
}
}
else{
console.log(response.error.message);
}
}
}, (error) => {
console.log('Login Failed'); // handle login failed here.
})
}
Solution 3:[3]
Pass a second function in subscribe to catch the error.
loginUser(user:any){
this.userService.loginUser(user).subscribe(
(response) => {
console.log("test");
if(response){
console.log(response.token);
if(response.token){
localStorage.setItem('currentUser',JSON.stringify(response));
if(response.user.role==='ADMIN'){
this.router.navigate(['/admindashboard']);
}else{
this.router.navigate(['/userdashboard']);
}
}else{
console.log("No Token");
}
}
},
(error)=>{
console.log(error.message);
}
)
}
Solution 4:[4]
You need to catch the error of the observable. Subscribing an observable takes an object with up to 3 properties, which itself take a function as value, the next handles good data, the error handles errors and the complete is a final call e.g.
const subscription = this.data.subscribe({
next: (v) => console.log(v),
error: (e) => console.error(e),
complete: () => console.info('complete'),
})
So you need to add an error handler to catch the condition you are talking about.
Reference:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dale K |
| Solution 2 | Surjeet Bhadauriya |
| Solution 3 | ranjeet8082 |
| Solution 4 | David Wolf |


