成功后如何导航 angular 订阅

how to navigate after success angular subscribe

Angular 8. 当用户更新模型时,我希望仅在更新数据库后将他们重定向回 dashboard 页面,以便他们可以看到新值。一旦用户被重定向到 dashboard 页面,我目前拥有它的方式就必须刷新浏览器才能看到更新。我以为我可以在 subscribe() 方法中执行此操作,但我似乎无法弄清楚..

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

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

}

我一直在 ERROR TypeError: Cannot read property 'navigate' of undefined

您需要使用箭头函数,否则 this 将上下文更改为您已定义 complete 方法的对象:

  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'])
    )

试试这个。