I'm using Angular with server-side rendering and TransferState to transfer http data from server to browser. Here is my code:
getProducts() {
let products = this.tstate.get(PRODUCT_KEY, null as any);
if (products) {
return of(products);
}
return this.http.post<any>(config.baseUrl+ 'product', {}).pipe(map(
data => {
this.tstate.set(PRODUCT_KEY, data as any);
return data;
}
))
}
In the first load, I get the data from http request. Then the state is initializing. After that, when the route changes, still transfer state keeps the data, so I can't send the request to get the data. Any idea how to reset transfer state in route changing?
You could listen to router events and unset cached data after navigation
constructor(private router: Router,
//...)
{
this.router.events.subscribe(evt => {
if (evt instanceof NavigationEnd)
{
this.tstate.remove(PRODUCT_KEY);
}
}
Or you could stop setting transfer data if you are client side
constructor(@Inject(PLATFORM_ID) private platformId: Object
//...)
{
}
getProducts() {
let products = this.tstate.get(PRODUCT_KEY, null as any);
if (products) {
this.tstate.remove(PRODUCT_KEY);
return of(products);
}
return this.http.post<any>(config.baseUrl+ 'product', {}).pipe(map(
data => {
if(!isPlatformBrowser(this.platformId)
{
this.tstate.set(PRODUCT_KEY, data as any);
}
return data;
}
))
}