Search code examples
angularinterfacehttp-headershttpclient

What can I replace RequestOptionsArgs with in this function?


Working on a rewrite of an existing angular application that is moving form Angular 4.3 to Angular 8. From my understanding the HttpClient is the way to go, but I'm having some trouble with some of the component classes. Like ConnectionBackend RequestOptions and RequestOptionsArgs. I'm not sure with what to replace them, or if I need to change code other than replacing the imports and type annotations.

A case in point is here:

import {RequestOptions, RequestOptionsArgs} from '@angular/http';
private getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
  if (options == null) {
    options = new RequestOptions();
  }
  if (options.headers == null) {
    options.headers = new Headers();
    // options.headers.append('Accept', 'application/json');
    // options.headers.append('Content-Type', undefined);
  }
  //to do get token 
  return options;
}

From what I can tell, it's needing to have request options, which doesn't necessarily mean just headers, but the only equivalent I've found is HttpHeaders but does that mean I should just pass around headers? How could this be refactored to accomplish the same task? It looks like this was intended to set default headers anyway.


Solution

  • Yes you have to use HttpHeaders like so:

    const headers = new HttpHeaders({
      responseType: 'application/json',
      headers: {
        'Accept': 'application/json',
        'Content-Type' : undefined
      }
    });
    this.httpClient.get('your-url', {headers});
    

    Options interface:

    {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe?: HttpObserve;
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
        withCredentials?: boolean;
    }