Created
April 14, 2023 23:58
-
-
Save chriseugenerodriguez/e0a31386f144766d6707c832813ae156 to your computer and use it in GitHub Desktop.
Network Interceptor for Offline Redirect (Angular)
This file contains 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, | |
HttpResponse, | |
HttpHandler, | |
HttpEvent, | |
HttpInterceptor | |
} from '@angular/common/http'; | |
import { Router } from '@angular/router'; | |
// RXJS | |
import { Observable } from 'rxjs/Observable'; | |
import { map } from 'rxjs/operators'; | |
@Injectable() | |
export class NetworkInterceptor implements HttpInterceptor { | |
constructor(private _router: Router) { } | |
intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> { | |
return next.handle(req).pipe( | |
map((event: HttpEvent<any>) => { | |
let onLine = navigator.onLine; | |
if (!onLine) { | |
this._router.navigate(['/offline']); | |
} | |
if (event instanceof HttpResponse) { | |
if (event.status === 524) { | |
this._router.navigate(['/offline']); | |
} | |
} | |
return event; | |
})); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment