简体   繁体   中英

Ionic Alert inside Interceptor

I'm intercepting network response in order to give feedback about network error.

I can't get the ionic alert module to work.

I think that the problem is that ionic-alert use a promise which is not resolved, but I don't know what is wrong with my implementation. The interceptor work. I can intercept all the request. The only problem is that I cannot see the alert poupup.

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import {Observable, throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AlertController } from '@ionic/angular';


@Injectable({
  providedIn: 'root'
})
export class RespinterceptorService {

  constructor(public alertController: AlertController) { }





  async mngerror(error: HttpErrorResponse){

    let input = error.statusText+error.name;

      const alert = await this.alertController.create({
      header: 'Alert',
      subHeader: 'Subtitle',
      message: input,
      buttons: ['OK']
    });

    await alert.present();



    return throwError(error);
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {


      return next.handle(req).pipe(
        catchError(this.mngerror)
      )
  };
}

您必须在类中实现 HTTPInterceptor。

export class RespinterceptorService implements HTTPInterceptor {

Did you provide your interceptor in your app module?

It should look like:

@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
  providers: [
            { provide: HTTP_INTERCEPTORS, useClass: RespinterceptorService, multi: 
                true }
    ],
    bootstrap: [AppComponent]
})
export class AppModule {}

Also as mentioned before you have to implement HTTPInterceptor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM