Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the { observe: 'response' } option globally in Angular 4.3+?

The first thought was to use an HttpInterceptor but the signature of the clone(...) method does not contain the observe option. Other than defining the { observe: 'response' } option for each request, I don't see an alternative yet ...

So, is there, if any, method to set the { observe: 'response' } option globally, e.g. via the HttpInterceptor?

clone(update: {
   headers?: HttpHeaders;
   reportProgress?: boolean;
   params?: HttpParams;
   responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
   withCredentials?: boolean;
   body?: T | null;
   method?: string;
   url?: string;
   setHeaders?: {
       [name: string]: string | string[];
   };
   setParams?: {
       [param: string]: string;
   };
}): HttpRequest<T>;
like image 941
Dalie Avatar asked Jan 31 '18 13:01

Dalie


People also ask

What is observe response in angular?

Observe Response HttpClient object allows accessing complete response, including headers. In the browser, response body is a JSON object, which can be copied to a typescript interface or class type. Response headers are key/value pairs.

What is Httpheaders angular?

HTTP Headers let the client and the server share additional information about the HTTP request or response. For example, we use the content-type header to indicate the media type of the resource like JSON, text, blob, etc.

What does HttpClient post return?

The HttpClient. post() returns Observable instance of given response type. On this page we will see injecting HttpClient , creating request body and passing HTTP options. We will also look into error handling. For the demo we will use Angular In-Memory Web API to post data.

What is HttpClient in angular?

What Is HttpClient? HttpClient is a built-in service class available in the @angular/common/http package. It has multiple signature and return types for each request. It uses the RxJS observable-based APIs, which means it returns the observable and what we need to subscribe it.


1 Answers

I know the question is old but very interesting.

I thought about the overridden of the httpClient Methods.

You just need to override the methods once. And all of the work will be done.

something like this for example for GET Method:

  overrideGetRequest() {
    const httpRequest = this.http.get.bind(this.http);

    this.http.get = function get<T = any>(url: string, options?: any): Observable<T> {
      let requestOptions = options || {};
      if(!('observe' in requestOptions)) {
      requestOptions = { ...requestOptions, observe: "response" };
      }
      return httpRequest(url, requestOptions);
    };
  }

And here is the Stackblitz example, where I have overridden the POST and GET methods of the httpClient.

https://stackblitz.com/edit/angular-interceptors-kknew1?file=app%2Fapp.component.ts

like image 71
Ashot Aleqsanyan Avatar answered Oct 05 '22 19:10

Ashot Aleqsanyan