Latest working login - frontend
Sun Jun 23 2024 14:02:53 GMT+0000 (Coordinated Universal Time)
Saved by @iamkatmakhafola
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { FlexLayoutModule } from '@angular/flex-layout';
import {jwtDecode} from 'jwt-decode';
@Component({
selector: 'app-login',
standalone: true,
imports: [
MaterialModule,
ReactiveFormsModule,
RouterLink,
CommonModule,
HttpClientModule,
FlexLayoutModule
],
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
loginFormGroup: FormGroup;
isLoading: boolean = false;
constructor(
private router: Router,
private userService: UserService,
private fb: FormBuilder,
private snackBar: MatSnackBar
) {
this.loginFormGroup = this.fb.group({
email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required],
});
}
ngOnInit() {}
async LoginUser() {
if (this.loginFormGroup.valid) {
this.isLoading = true;
this.userService.LoginUser(this.loginFormGroup.value).subscribe({
next: (result: any) => {
if (result && result.token) {
localStorage.setItem('User', JSON.stringify(result));
// Decode the JWT token to extract user information
const decodedToken: any = jwtDecode(result.token);
console.log('Decoded Token:', decodedToken);
const userId = decodedToken.userId;
const userTypeID = decodedToken.User_Type_ID;
console.log('User Type ID:', userTypeID);
console.log('User Type ID:', userTypeID);
this.loginFormGroup.reset();
// Navigate based on user type
if (userTypeID === "1") { // Ensure userTypeID is compared as string
this.router.navigateByUrl(`/OwnerHome/${userId}`);
} else if (userTypeID === "2") {
this.router.navigateByUrl(`/EmployeeHome/${userId}`);
} else if (userTypeID === "3") {
this.router.navigateByUrl(`/Home/${userId}`);
} else {
this.snackBar.open('Error: Invalid user type: Please register as an authorized user', 'Close', { duration: 5000 });
}
} else {
this.snackBar.open('Login failed', 'Close', { duration: 5000 });
}
},
error: () => {
this.isLoading = false;
this.snackBar.open('Login failed', 'Close', { duration: 5000 });
},
complete: () => {
this.isLoading = false;
}
});
}
}
}



Comments