The server (ssr), while rendering the page, does the request to the API, but the same request is done by browser as well, which means double request for the data that has been already fetched from server.
I found two solution to solve this problem.
First one is to use TransferHttpCacheModule, only thing I have to do is to add this module to appModule
Second one is to use transfer state api directly, which means that I have to add some logic manually depend on transfer state api in every service or resolver, which does http request. For example:
I have to change this resolver
@Injectable()
export class CourseResolver implements Resolve<Course> {
constructor(private coursesService: CoursesService) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Course> {
const courseId = route.params['id'];
return this.coursesService.findCourseById(courseId);
}
}
To this, to avoid second request from the browser.
@Injectable()
export class CourseResolver implements Resolve<Course> {
constructor(
private coursesService: CoursesService,
@Inject(PLATFORM_ID) private platformId,
private transferState:TransferState) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Course> {
const courseId = route.params['id'];
const COURSE_KEY = makeStateKey<Course>('course-' + courseId);
if (this.transferState.hasKey(COURSE_KEY)) {
const course = this.transferState.get<Course>(COURSE_KEY, null);
this.transferState.remove(COURSE_KEY);
return of(course);
}
else {
return this.coursesService.findCourseById(courseId)
.pipe(
tap(course => {
if (isPlatformServer(this.platformId)) {
this.transferState.set(COURSE_KEY, course);
}
})
);
}
}
}
My question is what is the difference between this two? which one is better? (why?) or maybe TransferHttpCacheModule does the same thing behind the scenes as the second solution?