angular - 当我路由到另一个组件时,我在一个组件中有 API 调用挂起,必须取消之前的 API 调用
问题描述
我有一个问题,比如我在一个组件中调用 API 假设它处于挂起状态,现在我正在路由到另一个页面,需要取消在上一个路由中进行的上一个 API 调用
我尝试使用 HttpCancelInterceptor
@Injectable()
export class HttpCancelInterceptor implements HttpInterceptor {
constructor(private httpCancelService: HttpCancelService) { }
intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> {
return next.handle(req).takeUntil(this.httpCancelService.onCancelPendingRequests())
}
}
@Injectable()
export class HttpCancelService {
private cancelPendingRequests$ = new Subject<void>()
constructor() { }
public cancelPendingRequests() {
this.cancelPendingRequests$.next()
}
public onCancelPendingRequests() {
return this.cancelPendingRequests$.asObservable()
}
}
在 app.component.ts
让它适用于我这样写的所有路线
this.router.events.subscribe(event => {
if (event instanceof ActivationEnd) {
this.httpCancelService.cancelPendingRequests()
}
})
我无法截取我用示例解释的 API
当我遵循上述代码时出现的结果
第 1 页:当我路由到另一个页面时,调用 3 API 都处于挂起状态(计数、金额、公告)只有 1 个 API 被取消
第 2 页:计数 API - 取消金额 API - 待定公告 API - 待定
预期结果:
第 1 页:计数、金额、公告 API - 处于待处理状态
第 2 页:计数、金额、公告 API - 已取消状态
所有取消都需要在 app.component.ts 中作为通用路由更改进行处理
请帮我解决这个问题
解决方案
您应该取消订阅第一个组件中的订阅。
向所有在其类代码中调用的private ngUnsubscribe = new Subject();
组件添加一个字段。.subscribe()
Observables
然后调用方法this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
。 ngOnDestroy()
例子:
import { Component, OnDestroy, OnInit } from '@angular/core';
// RxJs 6.x+ import paths
import { filter, startWith, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { Myservice} from '../my.service';
@Component({
selector: 'test-component',
templateUrl: './test.component.html'
})
export class TestComponent implements OnDestroy, OnInit {
private ngUnsubscribe = new Subject();
constructor(private myService: Myservice) { }
ngOnInit() {
this.myService.getData()
.pipe(
startWith([]),
filter(data=> data.length > 0),
takeUntil(this.ngUnsubscribe)
)
.subscribe(data=> console.log(data));
this.myService.getAnotherData()
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(anotherData=> console.log(anotherData));
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
将运算符添加为最后一个很重要,takeUntil
以防止运算符链中的中间可观察对象泄漏。
推荐阅读
- javascript - 'key' 未定义 no-undef setState ReactJS
- angular - Angular - 自定义内置语言环境
- python - 在python上计算以大写字母开头的单词
- azure - Sitecore 9 - 负载测试导致 502 错误
- ruby-on-rails - Rails:创建可以引用或可以是字符串的列
- r - 将“7-2014”转换为日期格式并在 R 中找到最小值
- java - 原因:不存在类型变量 T 的实例,因此 int[] 符合 T[]
- cognos - Cognos 数据源连接问题
- mongodb - MongoDB 基于文档值而不是显式条件匹配数组
- java - 使用 MockMvc StandaloneSetup 时 MockBean 未初始化服务 bean