Ionic 为什么Interceptor不与capacitor-community/http合作?

5n0oy7gb  于 2022-12-08  发布在  Ionic
关注(0)|答案(2)|浏览(205)

My problem is that my interceptors not working with library capacitor-community/http .
I develop my app in Ionic and how can you see I provide interceptor in module. This is really problem with this library because my interceptors working with HttpClient from angular. More you can see in codes and images.
Interceptor:

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

    constructor(
        private authService: AuthService,
    ) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        
    console.log("I am here");
    
    return next.handle(request).pipe( 
            catchError(err => {
                const error = err.message || err.statusText;

                return throwError(error);
            })
        );
    }
}

calling method:

this.authService.login(item.username, item.password).pipe(
    finalize(() => {
        console.log("end");
    }),
).subscribe();

service with @capacitor-community/http: enter image description here

login(username: string, password: string): Observable<any> {
    const options = {
        url:this.resourceUrl + "/login",
        data: {
            username: username,
            password: password
        },
        headers: { 'Content-Type': 'application/json' }
    };
    
    return from(Http.post(options));
}

service with httpClient from @angular/common/http: enter image description here

login(username: string, password: string): Observable<any> {
    return this.http.post<any>(this.resourceUrl + "/login", { username, password });
}

appModule:

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    HttpClientModule,
    IonicModule.forRoot(),
    AppRoutingModule,
  ],
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
  ],
  bootstrap: [AppComponent],
})
amrnrhlw

amrnrhlw1#

我遇到了同样的问题,我“黑”它的方式是:仅在登录或您的第一次请求时使用navite http,这通常是匿名的,之后使用angular http,拦截器工作时不会出现任何CORS问题。然而,最好的方法是为capaitor http专门构建拦截器

ix0qys7i

ix0qys7i2#

对我有效的解决方案是使用这个库:https://github.com/sneas/ionic-native-http-connection-backend#readme

相关问题