Reputation: 1235
I am trying to make a login component in angular 7. I have created all the necessary services for signup and login and they are working. But I also want to handle the situation when userid/email is not found in the database and show a message on the client side.
login.component.html
<div *ngIf="invalidLogin">Invalid username or email</div>
login.component.ts
constructor(private usersrv: UsersService) {}
onLogin() {
const user: UserDetails = {
userid: "user",
email: "[email protected]",
password: "123"
}
return this.usersrv.login(user)
.subscribe(
res => {
console.log('response found');
this.invalidLogin = false;
},
err => {
console.log('response not found');
this.invalidLogin = true;
}
);
}
user.service.ts
login(user) {
return this.http.post(`${this.url}/login`, user)
}
It works well when I enter valid user "email: "[email protected]"
and prints response found
on console but does not print response not found
when I enter invalid user which is not present in the database, like "email: "[email protected]"
.
It looks like it does not come in else part when there is no response for service and change this.invalidLogin accordingly. Please suggest how to handle this case.
Thanks
Upvotes: 0
Views: 1277
Reputation: 31
There are two solutions
In the first one you can throw an exception from the server side, if the user is invalid. In that case the following code works
return this.usersrv.login(user)
.subscribe(res => {
console.log('response found');
this.invalidLogin = false;
},
err => {
console.log('response not found')
this.invalidLogin = true;
});
}
In the second case the exception is thrown at the server side but the status code is set to 401 (unauthorized).In that case there is some changes in the code.Your service should look like this.
login(user){
return this.http.post(`${this.url}/login`, user,{observe: 'response'})
}
login.component.ts
constructor(private usersrv: UsersService) {}
onLogin() {
const user:UserDetails = {
userid: "user",
email: "[email protected]",
password: "123"
}
return this.usersrv.login(user)
.subscribe(res => {
if(res.status==200){
console.log('response found');
this.invalidLogin = false;
}
else{
console.log('response not found')
this.invalidLogin = true;
}
//status code should be 401 for unauthorized user
});
}
Status code should be 401 for unauthorized user. The above else clause is a generic one
Upvotes: 3
Reputation: 629
hi error is not else part of subscribe function, its trigger when exception occurred on server side or sent error by server or internet connectivity issue if you want handle this problem you have send data from server. e.g if email found then send true value server then check in subscribe you have send value from server isEmailFound check in subs function
return this.usersrv.login(user)
.subscribe(res => {
console.log('response found');
this.invalidLogin = res.isEmailFound;
},
err => {
console.log('something went wrong')
this.invalidLogin = false;
});
}
Upvotes: 0