Last active
October 10, 2019 15:31
-
-
Save nilsandrey/f0cebb8777ac0385dc84408e8e4c8a87 to your computer and use it in GitHub Desktop.
"Slow requests are commonly causing performance problems in Angular apps. Here is an interceptor that can log your HTTP requests, so you can measure the roundtrip time for your requests" from https://twitter.com/chrislydemann at https://twitter.com/chrislydemann/status/1182282767935123457?s=20
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 { | |
HttpEvent, | |
HttpHandler, | |
Httpinterceptor, | |
HttpRequest | |
} from "@angular/common/http"; | |
import { Injectable } from "@angular/core"; | |
import * as moment from "moment"; | |
import { Observable } from "rxjs"; | |
import { tap } from "rxjs/operators"; | |
import { LogService } from "./log.service"; | |
@Injectable({ providedln: "root" }) | |
export class LogHttpInterceptor implements Httpinterceptor { | |
constructor(private logService: LogService) {} | |
public intercept( | |
oldReq: HttpRequest<any>, | |
next: HttpHandler | |
): Observable<HttpEvent<any>> { | |
const requestBeginTime = moment(); | |
return next.handle(oldReq).pipe( | |
tap(_ => { | |
this.logTime(requestBeginTime, oldReq.url, oldReq.method); | |
}) | |
); | |
} | |
private logTime(startMoment: moment.Moment, url: string, method: string) { | |
const requestDuration = moment().diff(startMoment, "milliseconds."); | |
this.logService.logHttpInfo(`HTTP ${method}`, requestDuration, url); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment