Search code examples
angularauthenticationangular-routingrouter

Angular 9 (Angular Material) redirect user after signup doesnt't work


I use Angular 9 and Angular material mixed with bootstrap. After Signup the user in this steep, I redirect him to the login page, but somehow it does not work, it seems like the route navigation is ignored when I press the button

The signup.TS

onSubmit(){
        if(this.userName.invalid && this.email.invalid && this.password.invalid) 
        return;
        let credentials={
          userName: this.userName.value,
          email: this.email.value,
          password: this.password.value
        }
        this.auth.signUp(credentials).subscribe(data=>{
          this.router.navigate[('/login')]
          console.log('signed') -> this line works!
        })    
      }

The Auth Service: TS

        private currentUserSubject:BehaviorSubject<User>
      currentUser: Observable<User>
      constructor(private http: HttpClient) { 
        this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));   
         this.currentUser= this.currentUserSubject.asObservable(); 
      }

    isLoggedIn():boolean{
      const user = JSON.parse(localStorage.getItem('currentuser'));
      return (!user==null)?true:false
    }

    public get currentUserValue(): User {
      return this.currentUserSubject.value;
    }


    signUp(credentials:any){
      console.log(credentials)
      return this.http.post<any>('/users/register', credentials);
    }

    login(credentials){
      console.log(credentials)
      return this.http.post<any>('/users/authenticate', credentials)
      .pipe(map(user => {
        if (user)
          localStorage.setItem('currentUser', JSON.stringify(user));
        return user;
      }))
    }

    logOut(){
      localStorage.removeItem('currentUser')
      console.log('loggedout')
    }

The strange thing is that in the subscribe method there is a console log beneath the router instruction works well! Why it's not getting redirected? I have similar problems with the login; I mean after the users get logged there is no return URL neither 'home' component, still, the logs work...


Solution

  • You need to treat router.navigate() as a function, here you are treating it as an Array :P.

    this.router.navigate(['/login']);
    

    BTW: your conditions for validUser, email, etc doesn't seem right, I think there should be || instead of &&.