Angular 5-Http拦截器和行为主题问题

时间:2018-06-27 08:58:03

标签: http rxjs angular5 observable angular-http-interceptors

当我使用http拦截器(拦截http请求和响应)和行为主题(用于基于拦截器的2个服务之间的通信)时,我遇到了问题。我有一种情况,我需要监视应用程序中正在进行的所有http调用,并且仅在应用程序中没有其他http调用进行时才进行特定的http post调用。

我有拦截器服务,其中我拦截了所有http请求和响应,并且当没有调用发生时,计数器变量为0 then,使用行为主题ok $,并将其订阅到其他服务2中,然后从那里进行具体的http帖子调用。当ok $的值更改时,第二次不进行此订阅。

  

拦截器服务:

import { Injectable } from '@angular/core';
import { HttpResponse, HttpEvent, HttpClient, HttpHeaders, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject  } from 'rxjs';
import 'rxjs/add/operator/do';

@Injectable()
export class InterceptorService {
  counter: number = 0;
  public ok$: BehaviorSubject<any>;


  constructor() {
    this.ok$ = new BehaviorSubject(false);
}

  checkCounter() {

    if (this.counter === 0) {
       setTimeout(() => {
         this.checkCounterFinally();
       }, 1000);
    }
  }


  checkCounterFinally() {
    if (this.counter === 0) {
      this.ok$.next(true);
    }

  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (this.counter === -1)
      this.counter = 1;
    else
      this.counter++;
    return next.handle(req).do(
      (event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          console.log(event);
          this.counter--;
          this.checkCounter();
        }
      },
      (error: any) => {
        (event instanceof HttpErrorResponse)
        {
          if (error instanceof HttpErrorResponse) {
            if (error.status != 200) {
              console.log(error);
            }
          }
        }
      }
    );
  }

}
  

服务2:打个电话:

import { Injectable } from '@angular/core';
import { LogService } from '../common/log.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { InterceptorService } from './interceptor.service';


@Injectable()
export class WorkerService {


  data: string;
  storage = this.LogService.storage;
  RestUrl = // some url



  constructor(private service1: LogService, private httpClient: HttpClient,
    private interceptor: InterceptorService) {
     this.service1.logData.subscribe((val) => {

       this.storage.setItem("key", "value");
     });

   this.interceptor.ok$.subscribe((value) => {
      if (value === true) {
        this.getDataFromLocalStorage();
      }    
    });



  }

  getDataFromLocalStorage(): void {

    //getting data from the local storage and making rest call to server


  }


  pushDatatoServer(data: string) {

    this.httpClient.post(this.RestUrl, this.data, this.httpHeaderObjRequestParam )
      .subscribe((response) => {
        // do something

        }



  }





}

0 个答案:

没有答案