3
Authservice
login(user: User){
return this.http.post<any>(`${this.API_URL}`, {
email: user.username,
password: user.password
});
}
isUserLoggedIn(){
return this.http.get<any>(`${this.API_URL}/1`);
}
logoff(){
//this.loggedIn.next(null);
this.router.navigate(['/login']);
}
Logincomponent
onSubmit(){
this.submitted = true;
this.authService.login(this.loginForm.value).subscribe(r => {
if(r.success){
this.router.navigate(['/home']);
}
});
}
Auth Guard
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): any{
return this.authService.isUserLoggedIn()
.pipe(
map(res => {
if (res.isAuth){
return true;
}
this.router.navigate(['/login']);
return false;
})
);
}
- I have a Service (
AuthService
); - In the
LoginComponent
: Send the data to aAPI
to log in (sendusername
andpassword
) returningsucesso
if the user exists; - In the
Guard
: Other service (isUserLoggedIn()
) checks if the user is logged in and if thesessão
is still alive.
Is there another approach to user authentication in Angular 4+? Would this approach be used in most projects?
Could you transcribe the most important parts of the link in your reply? See We want answers that contain only links?
– Woss