-
-
Save datze/1484eb8535871b4ab72fc81e3ff1c571 to your computer and use it in GitHub Desktop.
An Angular 6+ interceptor to parse dates from server response.
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 { | |
HttpRequest, | |
HttpHandler, | |
HttpEvent, | |
HttpInterceptor, | |
HttpErrorResponse, | |
HttpResponse | |
} from '@angular/common/http'; | |
import { Observable } from 'rxjs'; | |
import { tap } from 'rxjs/operators'; | |
export class AngularDateHttpInterceptor implements HttpInterceptor { | |
// Migrated from AngularJS https://raw.githubusercontent.com/Ins87/angular-date-interceptor/master/src/angular-date-interceptor.js | |
iso8601 = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/; | |
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
return next.handle(req).pipe( | |
tap((event: HttpEvent<any>) => { | |
if (event instanceof HttpResponse) { | |
const body = event.body; | |
this.convertToDate(body); | |
} | |
}, (err: any) => { | |
if (err instanceof HttpErrorResponse) { | |
if (err.status === 401) { | |
} | |
} | |
}), | |
); | |
} | |
convertToDate(body) { | |
if (body === null || body === undefined || typeof body !== 'object') { | |
return body; | |
} | |
for (const key of Object.keys(body)) { | |
const value = body[key]; | |
if (this.isIso8601(value)) { | |
body[key] = new Date(value); | |
} else if (typeof value === 'object') { | |
this.convertToDate(value); | |
} | |
} | |
} | |
isIso8601(value) { | |
return (typeof value !== 'string')? false: this.iso8601.test(value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment