Angular 5 |使用HttpInterceptor渲染进度条

时间:2018-02-08 07:41:18

标签: angular rxjs rxjs5

我正在尝试使用HttpInterceptor在我的Angular 5应用程序中添加material progress-bar

每当有任何未完成的XHR请求时,进度条应该是可见的,并且在没有待处理的XHR请求时应隐藏/删除。

以下是我的HttpInterceptor实现,用于跟踪待处理的请求计数: -

import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
import 'rxjs/add/operator/publish';

@Injectable()
export class ProgressBatHttpInterceptorService implements HttpInterceptor {
  obs: Observable<number>; // PROBLEM: How to expose this as hot Obeservable ?
  private count = 0;

  constructor() {
    this.obs = Observable
      .create(observer => observer.next(this.count))
      .publish();
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.count++;   // increment the count here
    const observable = next.handle(req);
    observable.subscribe(() => {
    }, () => {
    }, () => {
      --this.count; // decrements the count.
    });
    return observable;
  }
}

AppComponent : -

import {Component} from '@angular/core';
import {ProgressBatHttpInterceptorService} from './progress-bat-http-interceptor.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(progress: ProgressBatHttpInterceptorService) {
    const obs = progress.obs;
    obs.subscribe(function (n) { // This never gets invoked.
      console.log(n);
    });
  }
}

ProgressBatHttpInterceptorService被注入AppComponent。在AppComponent构造函数中,我尝试订阅在ProgressBatHttpInterceptorService中创建的count observable。

我打算使用count Observable来有条件地隐藏进度条。

问题

.subscribe不会向控制台打印任何内容。

创建热门观察源以跟踪未完成的请求数量的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

您可以使用主题

obs: Subject<number>=new Subject();
 intercept(req: HttpRequest<any>, next: HttpHandler): 
 Observable<HttpEvent<any>> {
this.count++;   // increment the count here
const observable = next.handle(req).share(); // without share() , every call will be triggered twice
obs.next(this.count)
observable.subscribe(() => {
}, () => {
}, () => {
  --this.count; 
  obs.next(this.count)// decrements the count.
});
return observable;
}