transfer state not work in angular 17 and APIs are calling from client side

108 Views Asked by At

My project was on angular 15 version and SSR and transfer state was working fine and APIs called from server side but after migrate to angular 17 transfer state not work and same APIs are called in client

export const HOME = makeStateKey('home');
getHomeSections(forMobile: string):Observable<HomeSection[]>{
return this.dataStateService.checkAndGetData(HOME,
  this.http.get<ApiResponse<HomeSection[]>>(`core/Home`, {params: {forMobile}}).pipe(map(
    res => {
      return res.result;
    }
  ))
);

}

  checkAndGetData(key: string & { __not_a_string: never; __value_type?: void }, getDataObservable: Observable<any>, defaultValue: any = []) {
if (this.transferState.hasKey(key)) {
  return of(this.transferState.get(key, defaultValue));
} else {
  return getDataObservable.pipe(
    tap((data) => {
      if (this.isServer) {
        this.transferState.set(key, data);
      }
    })
  );
}

}

1

There are 1 best solutions below

0
On

I use this operator in RxJS. It saves the data to the cache on the server and also runs the query on the Frontend to revalidate the fresh data. To disable this refresh use of(transferState.get<T>(stateKey, {} as T)) if the key is found.

export const handleServerState = <T>(
  transferState: TransferState,
  stateKey: StateKey<T>,
  isServer: boolean,
): ((source$: Observable<T>) => Observable<T>) => {
  return (source$: Observable<T>) => {
    if (isServer) {
      return source$.pipe(tap(data => transferState.set(stateKey, data)))
    }

    if (transferState.hasKey(stateKey)) {
      return source$.pipe(
        startWith(transferState.get<T>(stateKey, {} as T)),
        tap(() => transferState.remove(stateKey)),
      )
    }

    return source$
  }
}

The usage is like this:

const HOME_SECTION_STATE_KEY = makeStateKey<ApiResponse<HomeSection[]>>('HOME_SECTION_STATE_KEY')

...

this.http.get('...').pipe(
  handleServerState(this.transferState, HOME_SECTION_STATE_KEY, isPlatformServer(this.platformId))
)