I have had the same problem for Angular universal support in angularspree
I followed these methods:
=> Create a TransferStateService, which exposes functions to set and get cache data.
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { isPlatformBrowser } from '@angular/common';
/**
* Keep caches (makeStateKey) into it in each `setCache` function call
* @type {any[]}
*/
const transferStateCache: String[] = [];
@Injectable()
export class TransferStateService {
constructor(private transferState: TransferState,
@Inject(PLATFORM_ID) private platformId: Object,
// @Inject(APP_ID) private _appId: string
) {
}
/**
* Set cache only when it's running on server
* @param {string} key
* @param data Data to store to cache
*/
setCache(key: string, data: any) {
if (!isPlatformBrowser(this.platformId)) {
transferStateCache[key] = makeStateKey<any>(key);
this.transferState.set(transferStateCache[key], data);
}
}
/**
* Returns stored cache only when it's running on browser
* @param {string} key
* @returns {any} cachedData
*/
getCache(key: string): any {
if (isPlatformBrowser(this.platformId)) {
const cachedData: any = this.transferState['store'][key];
/**
* Delete the cache to request the data from network next time which is the
* user's expected behavior
*/
delete this.transferState['store'][key];
return cachedData;
}
}
}
=> Create a TransferStateInterceptor to intercept request on server side platform.
import { tap } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpResponse
} from '@angular/common/http';
import { TransferStateService } from '../services/transfer-state.service';
@Injectable()
export class TransferStateInterceptor implements HttpInterceptor {
constructor(private transferStateService: TransferStateService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
/**
* Skip this interceptor if the request method isn't GET.
*/
if (req.method !== 'GET') {
return next.handle(req);
}
const cachedResponse = this.transferStateService.getCache(req.url);
if (cachedResponse) {
// A cached response exists which means server set it before. Serve it instead of forwarding
// the request to the next handler.
return of(new HttpResponse<any>({ body: cachedResponse }));
}
/**
* No cached response exists. Go to the network, and cache
* the response when it arrives.
*/
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
this.transferStateService.setCache(req.url, event.body);
}
})
);
}
}
=> Add that to the provider section in your module.
providers: [
{provide: HTTP_INTERCEPTORS, useClass: TransferStateInterceptor, multi: true},
TransferStateService,
]