【问题标题】:how to return data from angular HttpInterceptor and access in another angular component如何从角度 HttpInterceptor 返回数据并在另一个角度组件中访问
【发布时间】:2020-11-09 12:33:55
【问题描述】:

我有一个 HttpInterceptor,它正在计算请求和响应的总时间“totalTimeTakenByRequest”,我想在 UI 组件上显示此信息。我怎样才能做到这一点? 我的角度拦截器是:

export class InterceptorService implements HttpInterceptor
{
    totalTimeTakenByRequest:number=0;
       constructor() {`enter code here`
                     }
  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.totalTimeTakenByRequest=elapsed;
      }))
  }
}

【问题讨论】:

  • 我认为这不是最好的解决方案,但您可以将值存储到单独的服务中。将此服务注入到您的组件中,然后获取价值。
  • 我是 angular 新手,如果有任何最佳解决方案,您可以分享。实际上我实现了你的建议,但它不显示拦截器的第一个值并显示后续响应时间。
  • 我猜你正在覆盖你以前的值,因为你的所有请求只有一个拦截器。如果你把这些值放到一个数组中怎么办? this.totalTimeService.totalTimes.push(elapsed) 然后你可以在你想要的组件中渲染所有这些值
  • 这不会被覆盖,因为我们一次只执行一个请求和响应。
  • 这里的问题是如何在另一个组件中获得“totalTimeTakenByRequest”。目前我正在设置一个变量中的值,该值属于在此拦截器中注入的另一个服务,并在我想要的组件中获取值,但仅在第二个请求之后获取值。第一个请求在此变量中没有填充响应时间。

标签: angular angular-observable


【解决方案1】:

根据您的问题,您希望显示从您的InterceptorService 到组件的请求处理时间。

下面是使用来自rxjsSubject 运算符在componentsservices 之间共享数据的代码。另外,如果你想设置初始值,你也可以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 上的工作示例。

【讨论】:

    猜你喜欢
    • 2023-01-05
    • 2020-10-25
    • 2017-06-15
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2018-09-20
    相关资源
    最近更新 更多