可以使用RxJS和管道操作符来解决这个问题。下面是一个简单的示例,其中一个HTTP请求依赖于另一个请求的结果,这可能会导致重复的查询。
首先,在组件中创建一个流来处理这个问题,它将使用RxJS中的switchMap操作符:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Component({
selector: 'app-my-component',
template: `...`
})
export class MyComponent {
data$: Observable;
constructor(private http: HttpClient) {
this.data$ = this.http.get('/api/endpoint-1').pipe(
switchMap(data1 => this.http.get(`/api/endpoint-2/${data1.id}`))
);
}
}
在这个示例中,请求2将依赖于请求1的结果,并且如果在请求1之前发生了多重调用,那么它将只使用最后一次调用的结果。
可以进一步改进这个解决方案,以防止重复查询。为此,需要引入一个缓存变量:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { switchMap, filter, tap } from 'rxjs/operators';
@Component({
selector: 'app-my-component',
template: `...`
})
export class MyComponent {
private dataCache = new Map();
data$: Observable;
constructor(private http: HttpClient) {
const endpoint1$ = this.http.get('/api/endpoint-1').pipe(
tap(data1 => this.dataCache.set('endpoint1', data1))
);
const endpoint2$ = endpoint1$.pipe(
filter(() => !this.dataCache.has('endpoint2')),
switchMap(() => this.http.get(`/api/endpoint-
下一篇:Angular中图片不显示