angular 10: мой запрос не отправляется после подписки от observable в http-запросе в перехватчике

#angular #interceptor

#angular #перехватчик

Вопрос:

Я хочу перехватить все «удалить» http и раньше имел диалоговое окно подтверждения. Если пользователь нажимает «да», запрос отправляется, иначе ничего не добавляется.

Мой перехватчик выглядит как :

 @Injectable()
export class DeleteInterceptor implements HttpInterceptor {

    constructor(private dialog: MatDialog) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (req.method == 'DELETE') {
            this.dialog.open(ConfirmDeleteComponent).afterClosed().subscribe(result => {
                if (result) {
                    return next.handle(req); // don't send
                }
            });
        }else{
            return next.handle(req); // work correctly
        }
    }
}

  

Спасибо за вашу помощь,
Eva

Ответ №1:

 @Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor(private dialog: MatDialog) {
    }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // add custom header
     if (req.method == 'DELETE') {
            console.log(req)

            return this.dialog.open(ExampleDialogComponent).afterClosed().pipe(
              filter(res => res),
              switchMap(res =>                      next.handle(req) // don't send
)

            )
                
        }else{
            return next.handle(req); // work correctly
        }
  }
}
  

Это должно решить проблему.
В конце вам нужно вернуть observable.