根据您的问题,您希望显示从您的InterceptorService 到组件的请求处理时间。
下面是使用来自rxjs 的Subject 运算符在components 和services 之间共享数据的代码。另外,如果你想设置初始值,你也可以Behaviour操作符。
1. app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { InterceptorService } from './services/interceptor.service';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
{ provide: HTTP_INTERCEPTORS,
useClass: InterceptorService,
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }
2。 app.component.ts
import { Component } from '@angular/core';
import { DataShareService } from './services/data-share.service';
import { HttpService } from './services/http.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'TestStack';
elapsedTime: any = '';
data: any = '';
constructor(private dataShareService: DataShareService, private httpService : HttpService){
this.dataShareService.SharingData.subscribe((res: any) => {
this.elapsedTime = res;
});
}
GetData(){
this.httpService.getData().subscribe((res : any) => {
this.data = res;
});
}
}
3. app.component.html
<button (click)="GetData()">Get Data</button>
{{elapsedTime}}
<h2>Header Example</h2>
<pre>{{ data | json }}</pre>
服务和拦截器
1.拦截器.service.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpRequest, HttpHandler } from '@angular/common/http';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { DataShareService } from './data-share.service';
@Injectable()
export class InterceptorService implements HttpInterceptor {
constructor(private dataShareService : DataShareService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const started = Date.now()
return next.handle(req).pipe(
finalize(() => {
const elapsed = Date.now() - started;
this.dataShareService.SharingData.next(elapsed);
}))
}
}
2。 data-share.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataShareService {
SharingData = new Subject();
constructor() { }
}
3. http.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class HttpService {
constructor(private httpClient: HttpClient) { }
getData(){
return this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1');
}
}
注意:
对于API调用,我使用了JsonPlaceHolder免费api进行demo。
stackblitz 上的工作示例。