Search code examples
angularangular2-routingangular-routingangular12

Change route inside component according to its state. Is this possible?


On an Angular 12 application I have the following component:

export class SignUpComponent implements OnInit {

  form: FormGroup;

  result: boolean;

  constructor(private formBuilder: FormBuilder, private userService: UserService) { 

    this.form = this.formBuilder.group({ 
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(8)]],
    });

  }

  signUp() {

    if (this.form.valid) {

      this.userService.signUp({email: this.form.value.email, this.form.value.password).subscribe(
        
        (next) => { },

        (error) => { }

      )
    } 
  }    
} 

The route of this component is /signup.

Is it possible to change the route to:

  1. /signup/success with result variable set to true;
  2. /signup/failed with result variable set to false.

Always within the same component ...


Solution

  • You can achieve this using the Router and ActivatedRoute provided by Angular.

    Assuming you have configured your routes as below

    {path: 'signup/success', component: SuccessComponent } and
    {path: 'signup/failed', component: FailureComponent }

    Add this to the constructor of SignUpComponent

    constructor(private router: Router) { }

    Now, your signUp() method would look something like this.

    signUp() {
        if (this.form.valid) {
          this.userService.signUp({email: this.form.value.email, this.form.value.password).subscribe(
            (next) => { this.router.navigate(['/signup/success', {result: true}]); },
            (error) => { this.router.navigate(['/signup/failed', {result: false}]); }
          )
        } 
      } 
    

    Now in order to retrieve the value of the result parameter in either the SuccessComponent or FailureComponent, you can use ActivatedRoute provided by Angular by injecting it in the constructor of these two components as shown below:

    constructor(private route: ActivatedRoute) { }

    Now you can get the value of the result parameter in these components as shown below;

    resultValue = this.route.paramMap.get('result');