0

I'm trying to build an http-interceptor that waits with sending network requests until the onlinePipe returns true. The issue that I'm facing at the moment is that I can't seem to be able to come up with a solution that waits with returning a network request until the user is back online.

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest, } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { NetworkStatusService } from '../services/networkStatus.service';

@Injectable()
export class OfflineRequestInterceptor implements HttpInterceptor {
  constructor(
    private networkStatusService: NetworkStatusService,
  ) {
  }

  onlinePipe = this.networkStatusService.Online;

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const returnedRequest = new BehaviorSubject<Observable<HttpEvent<any>>>(null);

    this.onlinePipe.subscribe((online) => {
      if (online) {
        returnedRequest.next(next.handle(request));
      }
    });

    return returnedRequest.value;
  }
}

As referred to here I could try to implement some kind of mergeMap. Unfortunately I haven't been able to come up with a similar solution used in that situation.

Job
  • 467
  • 1
  • 6
  • 24
  • How you have structured currently it will not await the asynchronous response of `onlinePipe`. You need to instead simply return the `Observable` utilizing RxJS operators to map/create the final http response/event. You will not be executing `subscribe()` here. Possible duplicate of [Angular5 HttpInterceptor depending on the result of an Observable](https://stackoverflow.com/questions/49255762/angular5-httpinterceptor-depending-on-the-result-of-an-observable) – Alexander Staroselsky Mar 19 '19 at 16:46
  • @AlexanderStaroselsky could you give me an example of how I could implement that? I've tried doing something similar but I ran into issues given that it's an observable so I can't run a ``mergeMap`` directly on the Observable like in the answer you linked. – Job Mar 19 '19 at 18:54
  • You will probably need to provide the code around `onlinePipe`/`this.networkStatusService.Online`. Also, please share what you tried to do with `mergeMap`. `mergeMap` would be used along the lines of `this.onlinePipe.pipe(mergeMap(online) => {})`. You would not be able to do `this.onlinePipe.mergeMap()` or `this.onlinePipe.subscribe().mergeMap()`. You need to use it as a [pipeable operator ](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) – Alexander Staroselsky Mar 19 '19 at 19:58

0 Answers0