可以使用 RxJS 的 operator shareReplay() 来减少不必要的 HTTP 请求次数。
示例代码:
import { Observable } from 'rxjs';
import { shareReplay } from 'rxjs/operators';
@Component({
selector: 'app-component',
template: `
`
})
export class AppComponent {
data$: Observable;
constructor(private http: HttpClient) {}
ngOnInit() {
this.data$ = this.http.get('https://jsonplaceholder.typicode.com/posts').pipe(
shareReplay(1)
);
}
}
在上面的示例代码中,我们使用了 HttpClient 来发出 HTTP 请求,并使用了 async pipe 来将异步数据绑定到模板中。使用 pipe 函数调用 shareReplay() 运算符,它将返回一个带有缓存的可观察对象。这样,当多个组件订阅该可观察对象时,它只会发出一个 HTTP 请求。