httpClient oninit和ondestroy方法

时间:2019-05-20 23:19:38

标签: angular typescript httpclient angular-services

在Angular中,是否有类似ngOnit和ngOnDestroy的方法用于httpClient方法?基本上,我试图显示一个微调框,并在我进行的每个httpClient调用中隐藏该微调框。

1 个答案:

答案 0 :(得分:1)

您需要一个拦截器:

只需创建一个服务来设置加载程序是否需要显示或隐藏。在拦截器中设置此值,然后:

import { Injectable } from "@angular/core";
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Observable } from "rxjs";
import { finalize } from "rxjs/operators";

import { LoaderService } from '../services/loader.service';

@Injectable()
export class LoaderInterceptor implements HttpInterceptor {
    constructor(public loaderService: LoaderService) { }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.loaderService.show();
        return next.handle(req).pipe(
            finalize(() => this.loaderService.hide())
        );
    }
}
  

阅读this article以获取更多参考。