My service function is structured like this:
Please note: I am required to work with cookies
book(data: Spa): Observable<any> {
return this.http.post(`${environment.apiURL}:${environment.port}/${environment.domain}/abc/my.json`, data,
{
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
In each method where I have to send headers
, it looks messy and not following the DRY principle. Is there a way to automate this process by writing a generic CRUD
service? How can I achieve that?
I attempted the following approach:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { RequestOptions } from '@angular/http';
@Injectable({
providedIn: 'root'
})
export class CommonService {
constructor(private http: HttpClient) { }
post(url, params): Observable<any> {
return new Observable(observer => {
const headers = new Headers();
let options = new RequestOptions({ headers: this.createHeader(headers) });
this.http.post(url, params, options)
.subscribe(response => {
observer.next(response);
observer.complete();
}, (e) => {
observer.error(e);
});
})
}
createHeader(headers: Headers): Headers {
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return headers;
}
}
However, an error occurs during compilation on the line
let options = new RequestOptions({ headers: this.createHeader(headers) });
Type 'Headers' is missing the following properties from type 'Headers': keys, values, toJSON, getAll, and 2 more.ts(2740) interfaces.d.ts(61, 5): The expected type comes from property 'headers' which is declared here on type 'RequestOptionsArgs' (property) RequestOptionsArgs.headers?: Headers
Additionally, a warning is displayed:
RequestOptions is deprecated: see https://angular.io/guide/http (deprecation)