Wrap all already existing methods
panagulis72 opened this issue · 0 comments
panagulis72 commented
Hi,
I'm going to add the nativescript-https to my Nativescript/Angular app. I already have a very large number of API calls created using HTTPClient Module.
So, for example, my API calls are so structured:
firstApiCall() {
let httpParams = new HttpParams();
...adding parameters...
return this.http.get<number>(`my_url`, {
params: httpParams
})
.pipe(
map((data) => {
return data
})
);
}
secondApiCall(data) {
return this.http.post<boolean>('my_second_url', {
data: data
})
.pipe(
map((res) => {
return res;
})
);
}
with interceptor:
import { HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest } from
"@angular/common/http";
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headerSettings: { [name: string]: string | string[]; } = {};
for (const key of req.headers.keys()) {
headerSettings[key] = req.headers.getAll(key);
}
headerSettings['Authorization'] = 'Bearer .....................';
if (!(req.body instanceof FormData)) {
headerSettings['Content-Type'] = 'application/json';
}
const newHeader = new HttpHeaders(headerSettings);
const changedReq = req.clone({
headers: newHeader
});
return next.handle(changedReq);
}
}
To avoid manually changing each call (which would take an infinite amount of time) is there a way to create a wrapper?