请求是在服务器上执行的。
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来重新发出最后的值。然后,如果输入发生变化,覆盖属性的结果是一个新的observable被解析以返回新的值。
服务示例
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);
});
}
}
}
}
如果你打开Stackblitz的控制台,你可以看到,由于id是相同的,所以前7次调用都会返回相同的值,之后每次传递新的id都会改变。诚然这有点笨拙,但它可能会让你得到你需要的东西。