redirect to a route after api call in angular2

rgk picture rgk · Dec 17, 2016 · Viewed 11.2k times · Source

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.

Answer

tushar balar picture tushar balar · Dec 17, 2016
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