I'd like to know the best way to avoid nested subscriptions in the following scenario. I have an API rest call which can return a 401 unauthorized status code if the user token is expired. This is handled in the error callback of the subscription. When the error callback is called it ever opens an angular material dialog but only when the error received has the 401 code the user must be redirected to the login page on dialog close event. For the last purpose I subscribe to the afterClosed() stream of the dialogRef instance:
this.api.fetchData().subscribe({
next: (data) => {
// do something with data
},
error: (e: {status_code: number, message: string}) => {
const dialogRef = this.dialog.open(DialogErrorComponent, {
data: {text: e.message},
panelClass: 'my-dialog'
});
if (e.status_code === 401) {
dialogRef.afterClosed().subscribe((res) => {
this.router.navigate(['login']);
})
}
}
});
How can I refactor that code to avoid the nested subcriptions but keeping the purpose to subscribe to the afterClosed() only if the condition is met in the error callback?