I am working on a project which will need to migrate all instances of the old Http to utilize the new HttpClient provided by Angular. Async methods are declared within a DataService class like this:
@Injectable()
export class DataService {
constructor(private http: Http) { }
async getAsync<T>(resource: string, options?: RequestOptions): Promise<T> {
return this.http
.get(resource, options)
.map((response: Response) => response.json())
.catch(this.handleError).toPromise();
}
and used inside of another service class like this:
async getUser() {
try {
this.logger.debug('Getting User State...');
const userInfo = await this.dataService.getAsync<[Type Parameter]>(
this.constantService.urls.authenticatedUserUri, <RequestOptions>{ withCredentials: true }
);
this.logger.debug(JSON.stringify(userInfo));
this.authorizeUser(userInfo);
} catch (error) {
this.logger.debug(error);
}
}
I know that in order to use HttpClient I need to import HttpClientModule in the module that provides the DataService class and then import HttpClient within the service itself and inject it via the class's constructor. I also know that the line .map((response: Response) => response.json() )
is unnecessary, as JSON is now the default response type.
My main question is what to use in place of the RequestOptions object which is no longer supported in the HttpClient module. I'm assuming I'll have to utilize HttpHeaders and/or HttpParams in place of RequestOptions, but I'm not sure about the implementation. The line <RequestOptions>{ withCredentials: true }
is also throwing me off.
I'm going to continue researching and going through the documentation to try to find the proper solution, but I appreciate any help with this particular matter. Thanks!
Options is no longer typed
Just replace the RequestOptions
with any
.
In the documentation you can see the following:
request(first: string|HttpRequest<any>, url?: string, options: {
body?: any,
headers?: HttpHeaders|{[header: string]: string | string[]},
observe?: HttpObserve,
params?: HttpParams|{[param: string]: string | string[]},
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
} = {}): Observable<any>
As you can see, withCredentials
is still available and there is no type for options
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With