为什么switchMap不取消重复请求



请求在服务器上执行:

ngOnInit(): void {
this.route.paramMap
.pipe(
switchMap((params) => {
return this.spdModelManagerService
.getSpdModelManager()
.getOrderDefinitionVersions(params.get("orderid"));
}),
finalize(() => {
})
)
.subscribe((data) => {
console.log("aa");
});
}

如果多次执行f5或通过路由,请求总是发送到服务器,并且不会被switchMap ((params) => {})取消。所有的请求都会得到答案。

我应该使用解析器还是什么?如果用户长时间请求一条路线,它会发送大量请求

这是一种破解,但这与我在缓存某些请求时所做的类似。本质上,如果get的输入相同,并且响应始终相同,则可以在服务的属性内缓存可观察到的值,并使用shareReplay重新发出最后发出的值。然后,如果输入发生更改,则覆盖属性会导致解析新的可观察项以返回新值。

示例服务

import { Injectable } from "@angular/core";
import { Observable, timer, of } from "rxjs";
import { publishReplay, map, shareReplay } from "rxjs/operators";
@Injectable()
export class ExampleService {
private savedObs$: Observable<any>;
private lastId: number;
constructor() {}
get(id: number) {
const randomReturnValue = Math.random();
if (this.lastId !== id) {
this.lastId = id;
this.savedObs$ = of(id).pipe(
shareReplay(1),
map(x => randomReturnValue)
);
}
return this.savedObs$;
}
}

组件

import { Component } from '@angular/core';
import { ExampleService } from './example.service';
import { tap } from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
name = 'Angular';
constructor(private exampleService: ExampleService) {
// To show that the same value is returned for the first 7 calls to the observable
for (let i = 0; i < 15; i += 1) {
if (i < 7) {
this.exampleService.get(1).pipe(
tap(x => {
console.log(x);
})
).subscribe();
} else {
this.exampleService.get(i).subscribe(x => {
console.log(x);
});
}
}
}
}

如果您在Stacklitz中打开控制台,您可以看到由于id相同,前七个调用都返回了相同的值,然后每次传递新的id时都会更改。诚然,这有点草率,但它可能会让你得到你需要的。

https://stackblitz.com/edit/angular-6dioyr

最新更新