Let's say we have this Post component:
@Component({
template: `
<div
*ngIf="post$ | async as post"
[innerHTML]="post.content">
</div>
`,
})
export class Post implements OnInit {
post$!: Observable<Post>;
constructor(private http: HttpClient, private route: ActivatedRoute) {}
ngOnInit(): void {
this.post$ = this.route.paramMap.pipe(
switchMap((params) => {
const slug = params.get('slug') ;
return this.http.get<Post>(`${env.apiUrl}/posts/${slug}`);
})
);
}
}
When we pre-render posts pages:
ng run myapp:prerender --routes-file routes.txt
Their data are fetched and the HTML is generated successfully. But when we launch the generated static content, they still RE-fetch the data.
Is it possible to prevent that RE-fetch ? or it is not recommended ?
CodePudding user response:
It is built-in, use the TransferHttpCacheModule
It allows to serialize the data which has been fetched on server side in a script
element of the generated HTML code. Then in the browser, the TransferHttpCacheInterceptor
intercept every HTTP request and checks into that data if there is a corresponding entry. It uses <http_verb>.<url>
as the key.
Every cache entry is invalidated as soon as it has been used, so that future requests with the same <http_verb>.<url>
key are sent to the backend.