1
|
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
|
2
|
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
|
3
|
import { Observable, of } from 'rxjs';
|
4
|
import { tap } from 'rxjs/operators';
|
5
|
import { TransferState, makeStateKey, StateKey } from '@angular/platform-browser';
|
6
|
import { isPlatformServer } from '@angular/common';
|
7
|
|
8
|
@Injectable()
|
9
|
export class HttpInterceptorService implements HttpInterceptor {
|
10
|
constructor(private transferState: TransferState, @Inject(PLATFORM_ID) private platformId: any) {}
|
11
|
|
12
|
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
|
13
|
|
14
|
//console.info("intercept transferstate");
|
15
|
if (request.method !== 'GET') {
|
16
|
return next.handle(request);
|
17
|
}
|
18
|
|
19
|
const key: StateKey<string> = makeStateKey<string>(request.url);
|
20
|
|
21
|
const storedResponse = this.transferState.get<any>(key, null);
|
22
|
//console.info(key, storedResponse);
|
23
|
if (storedResponse) {
|
24
|
const response = new HttpResponse({body: storedResponse, status: 200});
|
25
|
if (!isPlatformServer(this.platformId)) {
|
26
|
//console.info("browser remove: ", key);
|
27
|
this.transferState.remove(key);
|
28
|
}
|
29
|
return of(response);
|
30
|
} else {
|
31
|
if (isPlatformServer(this.platformId)) {
|
32
|
return next.handle(request).pipe(tap((event) => {
|
33
|
//console.info("server add: ", key);
|
34
|
this.transferState.set(key, (<HttpResponse<any>>event).body);
|
35
|
}));
|
36
|
} else {
|
37
|
return next.handle(request);
|
38
|
}
|
39
|
}
|
40
|
}
|
41
|
}
|