angelnikolov / ts-cacheable

Observable/Promise Cache Decorator
https://npmjs.com/package/ts-cacheable
ISC License
340 stars 42 forks source link

Ionic 4: still hitting API #26

Closed lordcoste closed 5 years ago

lordcoste commented 5 years ago

Hi, I'm using the Cacheable decorator in one of my service but I always hit the real API.

I'm using Ionic 4 and angular 7.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Cacheable } from 'ngx-cacheable';
import { pipe } from 'rxjs';
import { map } from 'rxjs/operators';

import { Adv } from './adv.model';

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

  }

  @Cacheable()
  public getAdvs(place: number) {
    return this.http.get<Adv[]>('http://.../api/v1/advs/' + place)
      .pipe(map(advs => advs.filter(adv => adv.landingUrl !== null)));
  }
}

I've also tried without the pipe, but the result is the same. Could it have something to do with providedIn root and lazy loading?

Thanks for your help.

angelnikolov commented 5 years ago

Hey @lordcoste, I doubt it that it has something to do with the lazy loading since Cacheable is just a decorator and shouldn't be affected by it and it should start working once it loads lazily. Can you show me how you are invoking getAdvs?

lordcoste commented 5 years ago

sure:

this.placeService.getAdvs(place_id).subscribe((advs) => {
    console.log(advs);
});
angelnikolov commented 5 years ago

Hm, can you put a console.log in your method, like:

@Cacheable()
  public getAdvs(place: number) {
    console.log(place);
    return this.http.get<Adv[]>('http://.../api/v1/advs/' + place)
      .pipe(map(advs => advs.filter(adv => adv.landingUrl !== null)));
  }

and confirm that it really gets called multiple times with the same argument?

lordcoste commented 5 years ago

I see, I'm switching from one place to another:

/api/v1/advs/1
/api/v1/advs/2
/api/v1/advs/1 < here was expecting to be already in cache

if I increase maxCacheCount it works.

Can you confirm that this is the correct behaviour?

Most of my users will have just one place and setting maxCacheCount: 5 will cover everyone.

angelnikolov commented 5 years ago

Yes, this is the correct behaviour. If you just set it up with @Cacheable({}), i.e - no config, it will cache everything until the method is called with a new parameter - 2 in your case. If you set the maxCacheCount to 5, it will keep up to 5 parameter/response pairs in the cache.

lordcoste commented 5 years ago

Thank you :)