【发布时间】:2020-02-14 08:25:03
【问题描述】:
我的印象是 Angular Service 是 Singleton,但最近发现,或者至少看起来,该服务只是组件实例和组件子级的单例。
考虑以下代码:
const CACHE_REFRESH_INTERVAL = 1800000; //30 minutes
const CACHE_SIZE = 1;
const COMPANY_CACHE_KEY = 'company_cache_key';
@Injectable({
providedIn: "root"
})
export class CompanyService {
private companyCache: Map<string, Observable<any>> = new Map();
constructor(private httpClient: HttpClient) { }
public getAllCompanies(): Observable<CompanyViewModel[]> {
if (!this.companyCache[COMPANY_CACHE_KEY]) {
const timer$ = timer(0, CACHE_REFRESH_INTERVAL);
this.companyCache[COMPANY_CACHE_KEY] = timer$.pipe(
switchMap(_ => this.getAllCompaniesHttpRequest()),
shareReplay(CACHE_SIZE),
refCount(),
catchError(err => this.companyCache[COMPANY_CACHE_KEY] = undefined) //prevents storing error in cache
);
}
return this.companyCache[COMPANY_CACHE_KEY];
}
private getAllCompaniesHttpRequest(): Observable<CompanyViewModel[]> {
return this.httpClient.get<CompanyViewModel[]>(environment.endpoints.company.getAllCompanies());
}
}
比方说,ComponentA 通过组件的指导员获取此服务。当ComponentA 调用CompanyService.getAllCompanies() 方法时,结果将存储在companyCache 中。现在用户导航到一个新的 URL,ComponentA 被销毁,以及服务的实例。导航回ComponentA,并注入一个新的服务实例,companyCache 再次为空。
我的假设正确吗?我可以在整个应用程序中将服务设为单例吗?
【问题讨论】:
-
你的假设是正确的。我在两个应用程序中使用了这种模式的更简单版本。您如何获得
as well as the instance of the service的资格?你能设置一个堆栈闪电战来演示这个问题吗? -
只是补充一下,有趣的缓存模式。我在很大程度上已经从在我的应用程序中处理客户端缓存转移到使用电子标签,所以不必再担心这个了。
标签: angular typescript angular7