angular - 仅针对某些请求显示 Global Spinner
问题描述
我在常规 HTTP 调用上使用全局微调器。
装载机拦截器
import { Injectable } from '@angular/core';
import {
HttpResponse,
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { LoaderService } from '../services/loader.service';
@Injectable()
export class LoaderInterceptor implements HttpInterceptor {
private requests: HttpRequest<any>[] = [];
constructor(private loaderService: LoaderService) { }
removeRequest(req: HttpRequest<any>) {
const i = this.requests.indexOf(req);
if (i >= 0) {
this.requests.splice(i, 1);
}
this.loaderService.isLoading.next(this.requests.length > 0);
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.requests.push(req);
console.log("No of requests--->" + this.requests.length);
this.loaderService.isLoading.next(true);
return Observable.create(observer => {
const subscription = next.handle(req)
.subscribe(
event => {
if (event instanceof HttpResponse) {
this.removeRequest(req);
observer.next(event);
}
},
err => {
alert('error' + err);
this.removeRequest(req);
observer.error(err);
},
() => {
this.removeRequest(req);
observer.complete();
});
// remove request from queue when cancelled
return () => {
this.removeRequest(req);
subscription.unsubscribe();
};
});
}
}
装载机服务
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoaderService {
public isLoading = new BehaviorSubject(false);
constructor() { }
}
加载器组件
import { Component, OnInit } from '@angular/core';
import { LoaderService } from '../../services/loader.service';
@Component({
selector: 'app-my-loader',
templateUrl: './my-loader.component.html',
styleUrls: ['./my-loader.component.css']
})
export class MyLoaderComponent implements OnInit {
loading: boolean;
constructor(private loaderService: LoaderService) {
this.loaderService.isLoading.subscribe((v) => {
console.log(v);
this.loading = v;
});
}
ngOnInit() {
}
}
我有一些 URL 会在触发新通知时动态加载,我想要的是避免来自加载程序的这些特定调用,以防止微调器显示在这些特定请求上。
解决方案
有几种方法可以避免拦截器,这取决于您选择的要求。
您可以使用
HttpBackend
来进行 API 调用,而不是HttpClient
. 这是通过跳过你的拦截器来工作的,因此它会跳过你所有的拦截器,这些拦截器可能对你有问题,也可能没有问题。例如,您可以在请求中传递一个额外的参数,
skipLoadingInterceptor: boolean
如果存在,您可以跳过拦截器中负责设置加载动画的逻辑。
推荐阅读
- mysql - 要统计的具体 SQL 查询
- java - “Beautiful Triplets”问题中hackerrank的计时问题
- react-native - 将世博项目移动到本机反应后,收到警告“componentWillReceiveProps 已重命名”
- swift - 您可以通过类型中数据的大小来约束类型吗?
- postgresql - 更新一个字段时Postgresql删除行(级联更新)
- mysql - 如何在没有任何聚合函数的情况下在 Order By 后进行 Group By
- wordpress - Woocommerce - 可变产品在加载实际可变产品图像之前加载默认产品图像
- android - 如何请求关注嵌套滚动视图中当前扩展的容器布局?
- php - 自动检查登录处理程序上的用户角色,而不是检查每个页面上的会话?
- sap - Sybase - SAP ASE - 复制服务器:路由声明