Things I know (please correct me if I'm wrong, thank you :)):
HttpInterceptor
works in a way similar to Aspect-oriented programming;httpOptions
can be achieved for requests;clone()
can also be achieved for response;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?
Thanks to the help of @Sachin Gupta, I tested the interceptor
further with this demo.
What have been done:
auth-interceptor.ts
to add headers for the request;logging-interceptor.ts
added to track the request details and time cost;data-mocking-interceptor.ts
to stop the request to the server and return the mock data directly. 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
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))}) );
}
}