Angular的拦截器可以用来截获HTTP请求并对其进行处理。在应用程序中,我们可以使用拦截器来显示加载指示器或以某种方式修改请求。下面是一些使用拦截器的代码示例。
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
constructor(private loadingService: LoadingService) {}
intercept(request: HttpRequest, next: HttpHandler): Observable> {
this.loadingService.show();
return next.handle(request).pipe(
finalize(() => this.loadingService.hide())
);
}
}
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { LoadingInterceptor } from './loading.interceptor';
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: LoadingInterceptor, multi: true },
]
})
export class AppModule {}
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class LoadingService {
loading = false;
show() {
this.loading = true;
}
hide() {
this.loading = false;
}
}