angelnikolov/ts-cacheable

Refresh data

Closed this issue · 7 comments

Hello, when I'm adding a new item, it don't refresh data

const cacheBuster$ = new Subject<void>();

@Injectable({
  providedIn: 'root',
})
export class CollectsScheduleService {
  constructor(private http: HttpClient) {}

  @Cacheable({
    cacheBusterObserver: cacheBuster$,
  })
  getAll(crematoriumId: number): Observable<CollectSchedule[]> {
    return this.http.get<CollectSchedule[]>(
      `/collect-schedule/crematorium/${crematoriumId}`
    );
  }

  @CacheBuster({
    cacheBusterNotifier: cacheBuster$,
  })
  add(day: Day, zoneId: number): Observable<CollectSchedule> {
    return this.http.post<CollectSchedule>('/collect-schedule', {
      day,
      zoneId,
    });
  }
}

nvm, I thought it automatically refresh. I need to it manually

I don't know how refresh data, it still doesn't work.

I tried this:

@CacheBuster({
    cacheBusterNotifier: cacheBuster$,
  })
  add(day: Day, zoneId: number): Observable<CollectSchedule> {
    return this.http.post<CollectSchedule>('/collect-schedule', {
      day,
      zoneId,
    }).pipe(
        tap(() => this.getAll(1))
    );
  }

@ismailkoksal The cache will be cleared once the Observable returned from the method you've decorated with CacheBuster() has emitted.
The issue here is that the CacheBuster also works with tap() as you can see here https://github.com/angelnikolov/ts-cacheable/blob/master/cache-buster.decorator.ts#L17.
Basically, in your case, your tap() call will be executed before the CacheBuster one, because that was added to the Observable chain at a later stage. Therefore, you will still use the cache.

@angelnikolov I also tried this

this.collectsScheduleService.add().subscribe(() =>
    this.collectsScheduleService.getAll().subscribe()
);

Still don't work

Can you provide an example to my code on how to refresh after adding an item please

This is working

// service.ts

export const cacheBuster$ = new BehaviorSubject<void>(undefined);

@Cacheable({
  cacheBusterObserver: cacheBuster$,
})
getAll(): Observable<any[]> {
  // Return an Observable
}

@CacheBuster({
  cacheBusterNotifier: cacheBuster$,
})
add(): Observable<any> {
  // Return an Observable
}
// component.ts

constructor(private service: Service) {
  this.all$ = cacheBuster$.pipe(switchMap(() => service.getAll()));
}

@ismailkoksal Can you check this example?
https://stackblitz.com/edit/ngx-cacheable-my31me?file=src%2Fapp%2Fapp.component.ts
We have a get/update/get and it all works. It uses the latest version of ts-cacheable.