2019-09-30 12:48:26 +02:00
|
|
|
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
|
|
|
|
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
|
|
|
|
import { Observable, of } from 'rxjs';
|
|
|
|
import { tap } from 'rxjs/operators';
|
|
|
|
import { TransferState, makeStateKey, StateKey } from '@angular/platform-browser';
|
|
|
|
import { isPlatformServer } from '@angular/common';
|
|
|
|
|
2020-11-16 14:36:12 +01:00
|
|
|
@Injectable()
|
2019-09-30 12:48:26 +02:00
|
|
|
export class HttpInterceptorService implements HttpInterceptor {
|
|
|
|
constructor(private transferState: TransferState, @Inject(PLATFORM_ID) private platformId: any) {}
|
|
|
|
|
|
|
|
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
|
|
|
|
|
|
|
//console.info("intercept transferstate");
|
|
|
|
if (request.method !== 'GET') {
|
|
|
|
return next.handle(request);
|
|
|
|
}
|
|
|
|
|
|
|
|
const key: StateKey<string> = makeStateKey<string>(request.url);
|
|
|
|
|
|
|
|
const storedResponse = this.transferState.get<any>(key, null);
|
|
|
|
//console.info(key, storedResponse);
|
|
|
|
if (storedResponse) {
|
|
|
|
const response = new HttpResponse({body: storedResponse, status: 200});
|
|
|
|
if (!isPlatformServer(this.platformId)) {
|
|
|
|
//console.info("browser remove: ", key);
|
|
|
|
this.transferState.remove(key);
|
|
|
|
}
|
|
|
|
return of(response);
|
|
|
|
} else {
|
|
|
|
if (isPlatformServer(this.platformId)) {
|
|
|
|
return next.handle(request).pipe(tap((event) => {
|
|
|
|
//console.info("server add: ", key);
|
|
|
|
this.transferState.set(key, (<HttpResponse<any>>event).body);
|
|
|
|
}));
|
|
|
|
} else {
|
|
|
|
return next.handle(request);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-11-16 14:36:12 +01:00
|
|
|
}
|