为了避免重复订阅HTTP请求,可以使用RxJS的操作符shareReplay
来共享HTTP请求的结果,并在需要时订阅它。以下是一个使用Angular的示例代码:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { shareReplay } from 'rxjs/operators';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
data$: Observable;
constructor(private http: HttpClient) { }
ngOnInit() {
this.getData();
}
getData() {
if (!this.data$) {
this.data$ = this.http.get('https://api.example.com/data').pipe(
shareReplay(1)
);
}
this.data$.subscribe(data => {
// 在这里处理数据
});
}
}
在上面的示例中,我们使用shareReplay(1)
来共享HTTP请求的结果。第一次调用getData()
时,我们会发出HTTP请求并使用shareReplay
操作符共享结果。之后的调用将直接订阅共享的Observable而不会发出新的HTTP请求。
下一篇:Angular - 重构相对导入