第一次加载页面时或手动重新加载页面时,两次调用api都会调用api。 之后,当您转到其他组件并通过路由器链接返回家中时,不会再次调用该api,因此它可以正常工作,但是唯一的是,刷新后该api被调用了2次而不是1次。
数据服务
if($this->session->userdata('id')){
redirect('Panel_Controller/index', 'refresh');
}
家庭组件 我怎么称呼
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;
}
答案 0 :(得分:0)
您在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)
})
);
}