I am executing command
ng g interceptor error
where error is the name of interceptor
but facing the issue as below:
An unhandled exception occurred: Schematic "interceptor" not found in collection "@schematics/angular".
Do we have to install any package first ?
Looks like schematic support for generating interceptors was added in CLI 9.0.0
So, you can either upgrade to Angular 9, or write your own custom schematic, though in the short-term, if you can't / don't want to upgrade to Angular 9, it's probably easier to just write your interceptor yourself instead of generating it.
If someone looking to create a loading interceptor. Below here is a sample Loading interceptor create it like below and then inject LoadingInterceptor, LoadingIndicatorInterceptor in the provider's array of the parent module.
import { LoadingIndicatorService } from './file-path';
import { Injectable } from '@angular/core';
import {
HttpEvent,
HTTP_INTERCEPTORS,
HttpInterceptor,
HttpHandler,
HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { finalize, tap } from 'rxjs/operators';
@Injectable()
export class LoadingIndicatorInterceptor implements HttpInterceptor {
constructor(public loadingIndicatorService: LoadingIndicatorService) {}
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// emit onStarted event before request execution
this.loadingIndicatorService.onStarted(req);
return next
.handle(req)
// emit onFinished event after request execution
.pipe(
finalize(() => this.loadingIndicatorService.onFinished(req)), tap( r => {
})
);
}
}
export const LoadingInterceptor = {
provide: HTTP_INTERCEPTORS,
useClass: LoadingIndicatorInterceptor,
multi: true,
};
providers: [ LoadingInterceptor, LoadingIndicatorInterceptor] // This line should be in your module that you want the interceptor to be available
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With