How to get value of observable from service to HTTP interceptor

Viewed 84

I need to get value of observable from config.ts in HTTP Interceptor. I have no clue how to get value without subscribe, only I could get "Observable" I don't want to convert observable into promise or get this from state because I think it's not good practise, do you have some ideas how to do this?

Config.ts

interface State {
  clientVersion: string;
}

@Injectable({
  providedIn: 'root'
})
export class ConfigService {

  private _state: State;
  private readonly CONFIG_URL = 'http';

  clientVersion$: Observable<string> = this.getConfiguration().pipe(map(state => state.clientVersion));
  

  constructor( private http: HttpClient, private alertService: AlertService ) { }
  getConfiguration(): Observable<Config> {
    return this.http.get<Config>( this.CONFIG_URL )
        .pipe(
          map( config => this._state = {
            clientVersion: config?.clientVersion || '',
          }),
          catchError(() => {
            this.alertService.error( ' problem' );
            return of( this._state = {
              clientVersion: '',
            });
          }),
        );
  }

intereceptor.ts

export class CheckVersionInterceptor implements HttpInterceptor {

  configService = this.injector.get(ConfigService);
  modalService = this.injector.get(ModalService);
  private clientVersion;
  private clientNewVersion :string
  private readonly CONFIG_URL = 'URL';

  constructor(private injector: Injector) {}


  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      tap((event: HttpEvent<any>): void => {
        if (!(event instanceof HttpResponse) || request.url !== this.CONFIG_URL) { return ;}      
          this.clientVersion = this.configService.clientVersion$
          if(this.clientNewVersion !== this.clientVersion) {
            if(this.modalService.hasOpenModals()) {
              this.modalService.dismissAll();
              console.log(this.clientVersion);
            }
            this.modalService.open(NewAppNotyficationComponent)
          }
      })
    );
  }
}
1 Answers

Inside service

  getConfig$: Observable<State> = this._state ? of(this._state) : this.getConfiguration(); // Loading config only if it's not there 

Inside interceptor:

 constructor(private injector: Injector, private service:ConfigService ) {}

 ...

  if( request URL does not contain CONFIG_URL ) {
    this.service.getConfig$.pipe(
      mergeMap(config => next.handle(request).pipe(...)) //And you can use config inside your interceptor
    )
  } else { 
    return next.handle(request); // calling the get Config endpoint
  }
Related