Angular subscription to service is not called a 2nd time

41 Views Asked by At

I have a working service shared among different components. It works well in any component. The issue is once it has been called in any component, if I call it again, in the same component or in another one, it will be called (it appears in the console log as a successful response) but it won't appear in the Network tab of the browser developer tools. It will return old values.

My service :

@Injectable({
    providedIn: 'root'
  })

protected httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json; charset=utf-8',
      'Cache-Control': 'no-store, must-revalidate',
      'Pragma': 'no-cache',
      'Expires': 'Sat, 01 Jan 3000 00:00:00 GMT',
    }),
    //responseType: 'application/json',
    withCredentials: true
  };

getService(options?: object): Observable<any> { 
      const optionsHttp = Object.assign(options ? options : {}, this.httpOptions);
      let observable = this.http.get<any>(this.url, optionsHttp);
      return observable.pipe(
          map(response => {
          return response;
          }),
          retry(3));
    }

My subscription in a component :

getSubscription () {
    console.log('getSubscription'); // Check if this is logged
    this.subscription = this.service
      .getService(this.httpOptions)
      .subscribe(
        (response) => {
          if (response) {
            console.log(response);
          }
        },
        (error) => {
          console.warn('error', error);
        }
      );
  }

ngOnDestroy(): void {
        if (this.getSubscription ) {
            this.getSubscription .unsubscribe();
        }
}

Thank you!

I want the service to be called in the network anytime I will call it within any component.

1

There are 1 best solutions below

0
Hezy Ziv On BEST ANSWER

you have a cache problem, you can prevent caching by appending a unique query parameter to each request.

getService(options?: object): Observable<any> { 
    const uniqueParam = `cacheBuster=${new Date().getTime()}`;
    const cacheBustedUrl = `${this.url}?${uniqueParam}`;
    
    const optionsHttp = Object.assign(options ? options : {}, this.httpOptions);
    let observable = this.http.get<any>(cacheBustedUrl, optionsHttp);
    return observable.pipe(
        map(response => {
        return response;
        }),
        retry(3));
}