3

I need to redirect the user to a different component after processing (via api) the data user submitted through form. Below is the code I tried.

In component

onSubmit(model){
  if(model.valid === true) {
    this.SharedService.postFormdata(model).subscribe(
       data  => { console.log(data)},
       error => Observable.throw(error);   
    );
    this.router.navigate(['PublicPage']);
  }
}

However, after call completed, its not redirecting to PublicPage component. Any help please. Thanks.

ppovoski
  • 4,553
  • 5
  • 22
  • 28
rgk
  • 800
  • 1
  • 11
  • 32

2 Answers2

11
import { Router } from '@angular/router';

export class HeroesComponent {

  constructor(private router: Router) { }

  onSubmit(modal): void {
    if(model.valid === true) {
      this.SharedService.postFormdata(model).subscribe(
      (data) => { 
        // Page redirect when getting response
        this.router.navigate(['/PublicPage']);
      }, 
      (error) => {
        console.log("err", error);   
      });
    }

  }

}

For better understanding read this docs: Angular2 routing

Peter E
  • 63
  • 2
  • 6
tushar balar
  • 736
  • 3
  • 8
  • 24
3

First put your error outside of data block then If you want to redirect if it's success then add in

data => { this.router.navigate(['PublicPage']); }

Or if you want call anyhow, then use

() => {
        this.router.navigate(['PublicPage']);
}

So try like that:

onSubmit(model) {
    if (model.valid === true) {
        this.SharedService.postFormdata(model).subscribe(
            data => {
                console.log(data);
                this.router.navigate(['PublicPage']); // ON SUCCESS
            },
            error => Observable.throw(error),
            () => {
                    this.router.navigate(['PublicPage']); //ANYHOW WILL CALL
                }
        );
    }
}

Hope this will help.

Avnesh Shakya
  • 3,828
  • 2
  • 23
  • 31