Skip to content

Instantly share code, notes, and snippets.

@thisiszoaib
Last active January 30, 2022 07:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thisiszoaib/363978c4042021dee8cfd617539ad3f2 to your computer and use it in GitHub Desktop.
Save thisiszoaib/363978c4042021dee8cfd617539ad3f2 to your computer and use it in GitHub Desktop.
Loader Network Interceptor
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: NetworkInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoadingService {
private _loading = new BehaviorSubject<boolean>(false);
loading$ = this._loading.asObservable();
constructor() {}
startLoading() {
this._loading.next(true);
}
stopLoading() {
this._loading.next(false);
}
}
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { LoadingService } from './loading.service';
@Injectable()
export class NetworkInterceptor implements HttpInterceptor {
constructor(private loadingService: LoadingService) {}
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
this.loadingService.startLoading();
return next
.handle(request)
.pipe(finalize(() => this.loadingService.stopLoading()));
}
}
@muhammadawaisshaikh
Copy link

Cool 😎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment