I was modifying already working Angular 10 web-app into ionic native app, when I got some CORS issues. As I couldn't change anything on BE, I came across native-HTTP plugin Ionic has.
I followed Angular's instructions on how to make an interceptor and this article that explains how to implement both HttpClient and Ionic's native HTTP, but I run into new issues.
Using the code from article, TS is complaining about this line:
headers: nativeHttpResponse.headers
(property) headers?: HttpHeaders
Type '{ [key: string]: string; }' is missing the following properties from type 'HttpHeaders': headers, normalizedNames, lazyInit, lazyUpdate, and 12 more.ts(2740)
http.d.ts(3406, 9): The expected type comes from property 'headers' which is declared here on type '{ body?: any; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }'
Here's the whole native-http.interceptor.ts:
import { Injectable } from "@angular/core";
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent,
HttpResponse,
} from "@angular/common/http";
import { Observable, from } from "rxjs";
import { Platform } from "@ionic/angular";
import { HTTP } from "@ionic-native/http/ngx";
type HttpMethod =
| "get"
| "post"
| "put"
| "patch"
| "head"
| "delete"
| "upload"
| "download";
@Injectable()
export class NativeHttpInterceptor implements HttpInterceptor {
constructor(private nativeHttp: HTTP, private platform: Platform) {}
public intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (!this.platform.is("cordova")) {
return next.handle(request);
}
return from(this.handleNativeRequest(request));
}
private async handleNativeRequest(
request: HttpRequest<any>
): Promise<HttpResponse<any>> {
const headerKeys = request.headers.keys();
const headers = {};
headerKeys.forEach((key) => {
headers[key] = request.headers.get(key);
});
try {
await this.platform.ready();
const method = <HttpMethod>request.method.toLowerCase();
// console.log(‘— Request url’);
// console.log(request.url)
// console.log(‘— Request body’);
// console.log(request.body);
const nativeHttpResponse = await this.nativeHttp.sendRequest(
request.url,
{
method: method,
data: request.body,
headers: headers,
serializer: "json",
}
);
let body;
try {
body = JSON.parse(nativeHttpResponse.data);
} catch (error) {
body = { response: nativeHttpResponse.data };
}
const response = new HttpResponse({
body: body,
status: nativeHttpResponse.status,
headers: nativeHttpResponse.headers, <--------
url: nativeHttpResponse.url,
});
// console.log(‘— Response success’)
// console.log(response);
return Promise.resolve(response);
} catch (error) {
if (!error.status) {
return Promise.reject(error);
}
const response = new HttpResponse({
body: JSON.parse(error.error),
status: error.status,
headers: error.headers,
url: error.url,
});
return Promise.reject(response);
}
}
}
Here's how my app.module.ts
looks like:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { IonicModule } from '@ionic/angular';
import { HTTP } from '@ionic-native/http/ngx';
import { CoreModule } from './core/core.module';
import { SharedModule } from './shared/shared.module';
import { AppComponent } from './app.component';
import { PageNotFoundComponent } from './shared/page-not-found/page-not-found.component';
import { appRoutes } from './app.routes';
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
SharedModule,
CoreModule,
RouterModule.forRoot(
appRoutes
),
IonicModule.forRoot()
],
providers: [HTTP],
declarations: [
AppComponent,
PageNotFoundComponent
],
bootstrap: [AppComponent]
})
export class AppModule { }
Andd here is how my core.module.ts
(where I want to use interceptor) looks like:
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { HTTP_INTERCEPTORS, HttpClientModule } from "@angular/common/http";
import { NativeHttpInterceptor } from "./service/native-http.interceptor";
import { AuthService } from "./service/auth.service";
import { ApiService } from "./service/api.service";
import { AuthGuardService } from "./service/auth-guard.service";
import { AuthInterceptor } from "./service/auth-interceptor";
import { WindowRef } from "./service/window-ref-service";
@NgModule({
imports: [CommonModule, HttpClientModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: NativeHttpInterceptor,
multi: true,
},
AuthService,
ApiService,
AuthGuardService,
WindowRef,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true,
},
],
})
export class CoreModule {}
Angular's HttpRequest
has an awkwardly designed API. Specifically, its constructor requires an instance of Angular's HttpHeaders
, instead of accepting an object of headers.
Therefore, the correct code in your case would be
const response = new HttpResponse({
body,
status: nativeHttpResponse.status,
headers: new HttpHeaders(nativeHttpResponse.headers),
url: nativeHttpResponse.url
});
I would argue that this is bad API design plain and simple. It deviates from commonly used corresponding APIs such as fetch
, increases coupling, and is not remotely idiomatic, while forcing you to write boilerplate. By contrast, the Ionic Native team took the right approach by specifying headers as an object.