角HttpInterceptor等待订阅结果

时间:2019-03-19 16:43:24

标签: angular typescript rxjs angular-http-interceptors

我正在尝试构建一个HTTP拦截器,等待发送网络请求,直到onlinePipe返回true。我目前面临的问题是,我似乎无法提出一种解决方案,该解决方案需要等待返回网络请求,直到用户重新联机。

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;
  }
}

here所述,我可以尝试实现某种mergeMap。不幸的是,在这种情况下,我无法提出类似的解决方案。

0 个答案:

没有答案