redirect to a route after api call in angular2

夙愿已清 提交于 2019-12-05 21:26:34
tushar balar
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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!