angular - 为什么使用该服务缓存http请求时api会被调用2次
问题描述
当页面第一次加载或手动重新加载页面时,api 被调用 2 次,这两个 get 请求。之后,当您转到其他组件并通过路由器链接返回家中时,不会再次调用 api,因此它可以工作,但唯一的问题是在刷新时,api 被调用 2 次而不是 1 次。
数据服务
import { Injectable } from '@angular/core';
import { HttpClient, HttpBackend } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { Observable, of } from 'rxjs';
public responseCache = new Map();
constructor(private http: HttpClient, private handler: HttpBackend) {
this.http = new HttpClient(this.handler);
}
getTimeZone(): Observable<any> {
const URL = environment.BACKEND_HOST + 'api/timezone';
const fromCache = this.responseCache.get(URL);
if (fromCache) {
return of(fromCache);
}
const response = this.http.get<any>(URL);
response.subscribe(res => this.responseCache.set(URL, res));
return response;
}
Home 组件 我如何称呼它
this.data.getTimeZone().subscribe((data: any)=> {
this.timezones = data;
})
解决方案
您subscribe
一次response
进入getTimeZone
并返回response
,然后subscribe
再次使用this.data.getTimeZone().subscribe(...)
. 这就是它被调用两次的原因。
您可以使用map()
或可tap()
管道操作符getTimeZone
而不是订阅它:
getTimeZone(): Observable<any> {
const URL = environment.BACKEND_HOST + 'api/timezone';
const fromCache = this.responseCache.get(URL);
if (fromCache) {
return of(fromCache);
}
const response = this.http.get<any>(URL);
return response.pipe(
tap(res => {
this.responseCache.set(URL, res)
})
);
}
推荐阅读
- visual-studio-code - ESLint 在 JHipster 应用程序中无法在 VS Code 中工作
- azure-cosmosdb - Cosmos DB - 慢计数
- javascript - 在我的代码中,相机可以在点击时旋转,但它会立即将旋转设置为 90 度,我怎样才能让它平滑过渡
- c++ - C++ ncurses:带有特殊字符的 printw 产生'�~T~B'
- javascript - Javascript - 从 json 创建父子导航
- ios - 两个人如何使用相同的 bundle ID 处理同一个 Xcode 项目
- php - FPDF 多单元格重叠
- react-native - 如何在firebase中设置规则以响应本机
- node.js - 在 Azure 上调用 nodejs API 的连接关闭错误
- linux - 如何根据字数在第一个句点字符处拆分行并在结果行中重复该过程(在模式空间中)