Subscribe method not working in MEAN stack application

41 Views Asked by At

I have created a backend for my application and am now developing the frontend. I am trying to do the register component of my application.

This is my Register Component with me attempting to register the user. The problem I am encountering is that when the OnRegisterSubmit method is called, the user is actually created and written to the database, but the other code doesn't work but I don't think the .subscribe() method is working 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;
  
  }
}

This 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 });
  }
  
}

And lastly my user route:

// 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 knows why this is happening, I would appreciate the help. Thank you.

If you do need more information, feel free to ask.

1

There are 1 best solutions below

0
oksd On

Try this:

.subscribe({
    next: (v) => console.log(v),
    error: (e) => console.error(e),
    complete: () => console.info('complete') 
})