要在Angular 6中使用http.get获取相同的数据而不需要每次都查询API,可以使用RxJS的缓存操作符。以下是一个示例解决方法:
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
private cachedData: Observable;
shareReplay
操作符来缓存数据,并使用map
操作符将响应转换为你需要的格式:getData(): Observable {
if (!this.cachedData) {
this.cachedData = this.http.get('your-api-url').pipe(
map(response => {
// 对响应进行转换
// 例如,如果响应是一个对象数组,你可以使用下面的代码来转换为一个简单的数组:
return response.map(item => item.name);
}),
shareReplay(1) // 缓存最近的1个响应
);
}
return this.cachedData;
}
getData
方法来获取数据即可:getData(): void {
this.service.getData().subscribe(data => {
// 使用缓存的数据
console.log(data);
});
}
通过这种方式,第一次调用getData
方法时,数据将会从API中获取并缓存起来。随后的调用将直接从缓存中获取数据,而不会再次查询API。