Currently, I have completed the backend development of my application and am now working on the frontend. My focus at the moment is on implementing the register component within my application.
Below is the code snippet for my Register Component where I am trying to register a user. The issue I'm facing is that although the OnRegisterSubmit method successfully creates and writes the user data to the database, the remaining code doesn't seem to work as expected, leading me to suspect that the .subscribe() method may not be functioning correctly.
export class RegisterComponent implements OnInit {
username: String | null = null;
password: String | null = null;
firstname: String | null = null;
lastname: String | null = null;
constructor(private validateService: ValidateService,
private authService: AuthService,
private router: Router
){}
ngOnInit(){}
onRegisterSubmit(){
const user = {
username: this.username,
password: this.password,
firstname: this.firstname,
lastname: this.lastname
}
if(!this.validateService.validateRegister(user)){
alert('Please fill in all fields');
return;
}
//Register User
this.authService.registerUser(user).subscribe(data => {
if((data as any).success ) {
// Registration was successful
alert('You are now registered');
this.router.navigate(['/login']);
} else {
// Registration failed
alert('Something went wrong');
this.router.navigate(['/register']);
}
});
return null;
}
}
The following is my auth.service:
interface User {
username: String | null;
password: String | null;
firstname: String | null;
lastname: String | null;
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
authToken: any;
constructor(private httpClient: HttpClient) { }
registerUser(user: User) {
const headers = new HttpHeaders().set('Content-Type', 'application/json');
return this.httpClient.post('https://localhost:3000/api/users/signup', user, { headers });
}
}
Lastly, here's my user route implementation:
// Create new user
router.post('/signup', async(req,res) => {
const {error} = validateUser(req.body);
if (error) return res.status(400).json(error.details[0].message);
const isUnique = (await User.count({username: req.body.username})) === 0;
if(!isUnique)
return res
.status(401)
.json({error: 'The username or password is not valid'});
try{
const user = new User(req.body);
user.password=await hashPassword(user.password);
await user.save();
} catch(err) {
return res.status(500).json(err);
}
res.status(200);
})
If anyone has insights into why this issue is occurring, your assistance would be greatly appreciated. Thank you.
If additional information is required, please feel free to inquire.