how to navigate after success angular subscribe

Viewed 1200

Angular 8. When a user updates a model I want them to be re-directed back to a dashboard page only after the database is updated so that they can see the new values. THe way I currently have it once the user is redirected to the dashboard page you have to refresh the browser to see updates. I thought i could do this inside the subscribe() method but i cant seem to figure it out..

  constructor(
    private restaurantservice: RestaurantService,
    private router: Router
  ) { }

this.restaurantservice.restaurantedit(id, formData).subscribe({
  complete(){
    this.router.navigate(['/ownerdashboard'])
  }
})

}

i keep getting ERROR TypeError: Cannot read property 'navigate' of undefined.

2 Answers

You need to use arrow function else this changes context to object on which you have defined complete method:

  constructor(
    private restaurantservice: RestaurantService,
    private router: Router
  ) { }

this.restaurantservice.restaurantedit(id, formData).subscribe({
  complete: () => { // here you need to use arrow function
    this.router.navigate(['/ownerdashboard'])
  }
})
.subscribe(value => console.log(value),
           error => console.log(error),
           () => this.router.navigate(['/ownerdashboard'])
    )

Try this.

Related