Browse Source

Add http param encoder option to rest service

pull/10867/head
muhammedaltug 4 years ago
parent
commit
0294df6ffe
  1. 11
      npm/ng-packs/packages/core/src/lib/models/rest.ts
  2. 24
      npm/ng-packs/packages/core/src/lib/services/rest.service.ts

11
npm/ng-packs/packages/core/src/lib/models/rest.ts

@ -1,10 +1,11 @@
import { HttpHeaders, HttpParams } from '@angular/common/http';
import { HttpHeaders, HttpParameterCodec, HttpParams } from '@angular/common/http';
export namespace Rest {
export type Config = Partial<{
apiName: string;
skipHandleError: boolean;
observe: Observe;
httpParamEncoder?: HttpParameterCodec;
}>;
export const enum Observe {
@ -20,6 +21,8 @@ export namespace Rest {
Text = 'text',
}
export type Params = HttpParams | { [param: string]: any };
export interface Request<T> {
body?: T;
headers?:
@ -28,11 +31,7 @@ export namespace Rest {
[header: string]: string | string[];
};
method: string;
params?:
| HttpParams
| {
[param: string]: any;
};
params?: Params;
reportProgress?: boolean;
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
url: string;

24
npm/ng-packs/packages/core/src/lib/services/rest.service.ts

@ -1,4 +1,4 @@
import { HttpClient, HttpRequest } from '@angular/common/http';
import { HttpClient, HttpParameterCodec, HttpParams, HttpRequest } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@ -43,18 +43,22 @@ export class RestService {
.request<R>(method, api + request.url, {
observe,
...(params && {
params: Object.keys(params).reduce((acc, key) => {
const value = params[key];
if (isUndefinedOrEmptyString(value)) return acc;
if (value === null && !this.options.sendNullsAsQueryParam) return acc;
acc[key] = value;
return acc;
}, {}),
params: this.getParams(params, config.httpParamEncoder),
}),
...options,
} as any)
.pipe(catchError(err => (skipHandleError ? throwError(err) : this.handleError(err))));
}
private getParams(params: Rest.Params, encoder?: HttpParameterCodec): HttpParams {
const httpParams = encoder ? new HttpParams({ encoder }) : new HttpParams();
return Object.keys(params).reduce((acc, key) => {
const value = params[key];
if (isUndefinedOrEmptyString(value)) return acc;
if (value === null && !this.options.sendNullsAsQueryParam) return acc;
acc = acc.set(key, value);
return acc;
}, httpParams);
}
}

Loading…
Cancel
Save