-
-
Save ravivit9/592f09704db6664c1f1618475da9dfa7 to your computer and use it in GitHub Desktop.
Loader Network Interceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@NgModule({ | |
declarations: [AppComponent], | |
imports: [ | |
BrowserModule | |
], | |
providers: [ | |
{ | |
provide: HTTP_INTERCEPTORS, | |
useClass: NetworkInterceptor, | |
multi: true | |
} | |
], | |
bootstrap: [AppComponent] | |
}) | |
export class AppModule {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment