angularangular-httpclient-interceptors

mock the server response even the server is unreachable


Things I know (please correct me if I'm wrong, thank you :)):

My problems

I want to test some libraries while their related servers can be down sometimes when developing I just care about the data no interaction with server is okay

Is it possible that I can just return a mock data already prepared without requesting the server when the request met some patterns even the service lies in other libraries?

My Requirements

Updated 2019-01-15

Thanks to the help of @Sachin Gupta, I tested the interceptor further with this demo.

What have been done:


Solution

  • Have a look at this.

    https://stackblitz.com/edit/angular-json-http-response-catch

    If the server is reachable, the data is populated, otherwise mocked is sent as response

    Interceptor

    export class NoopInterceptor implements HttpInterceptor {
    
      intercept(req: HttpRequest<any>, next: HttpHandler):
        Observable<HttpEvent<any>> {
          let response = new HttpResponse();
          response = response.clone({body: [{"sads":"ewre"}]});
       
        return next.handle(req).pipe(catchError((err) => {return of(response).pipe(delay(10))}) );
      }
    }