Search code examples
angulartypescript

Elegant middleware for handling HTTP response in Angular 5.2.9


I need to handle many HTTP responses in the same way, in different classes and files, which is frustrating. So I wonder if I can customize HttpClient and make such a middleware handles tasks as followed:

this.http.get<any>('/api/ping/').subscribe((response) => {
  if (response.status_code == 302) {
    this.router.navigate([ response.data.redirectUrl ]);
  }
});

I decided to use Proxy object, but it only came to me that Proxy is not yet implemented in TypeScript 2.5.3.

Please show me either a way to customize behaviours of HttpClient or a workaround for proxy object in TypeScript 2.5.3, thanks in advance.


Solution

  • This has nothing to do with TypeScript version. Proxy is ES6 feature that cannot be transpiled or polyfilled. If the project is configured with ES5 target, Proxy cannot be used.

    This can be achieved by reusing common code in service classes, since they are usually used to do API requests.

    In case this should be done for all requests, which may or may not be desirable because this also affects third-party code, interceptors can be used:

    @Injectable()
    export class RedirectInterceptor implements HttpInterceptor {
      constructor(protected router: Router) {}
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).do((response) => {
          if (response.status_code == 302 && response.data.redirectUrl) {
            this.router.navigate([response.data.redirectUrl]);
          }
        });
      }
    }
    
      ...
      providers: [
        [{ provide: HTTP_INTERCEPTORS, useClass: RedirectInterceptor, multi: true }],
      ],  
      ...