自动初始化BehaviorSubject来缓存全局数据

发布于 2025-01-15 07:15:52 字数 1910 浏览 6 评论 0原文

简化的用例:

  1. 我有带有多个模块的 Angular 应用程序,大多数(不是全部)模块使用机场列表,
  2. 我想创建一个 global-cache.service.ts 并将机场列表缓存在BehaviorSubject 将作为 Observable 公开。我只想在用户登陆订阅该 Observable 的组件时初始化 BehaviorSubject (点击数据库)(而不是在服务控制器中初始化它)

这是起点,无法让它工作(请参阅 this.getAirpotsFromDB() 调用后的注释):

global-cache.service.ts

airports: BehaviorSubject<string[]> = new BehaviorSubject(null);
get airports$(): Observable<string[]> {
  if (this.airports.getValue() == null) {
    //get list from db, and initialize the subject
    this.getAirportsFromDB();
    //**PROBLEM:** how do I return `this.airports.asObservable()` after it's initialized with data from the call above or return it from inside the call?
  }
  else{
    //list initialized, emit from subject (don't hit db)
    return this.airports.asObservable();
  }
}

getAirportsFromDB() {
  this.http.get<string[]>('/api/airports').subscribe((_result) => {
    this.airports.next(_result);
  });
}

myComponent1.ts

//imports global-cache.service but never subscribes to airports$ (service has many other arrays that are used here)
//User lands here first, `getAirportsFromDB()` never gets called, user goes to myComponent2

myComponent2.ts

...
airports$: any = this.globalCacheService.airports$;
//subscribed in html `airports$ | async`
...
//user lands here, `getAirportsFromDB()` is called, `airports` BehaviorSubject is initialized
//user then goes to myComponent3

myComponent3.ts

...
airports$: any = this.globalCacheService.airports$;
//subscribed in html `airports$ | async`
...
//`airports` BehaviorSubject emits last value (initialized in Component2). `getAirportsFromDB()` does not get called again

Simplified use case:

  1. I have Angular app with multiple modules, most (not all) of the modules use a list of airports
  2. I want to create a global-cache.service.ts and cache the airport list in BehaviorSubject which will be exposed as Observable. I only want to initialize the BehaviorSubject (hit the DB) when user lands on component that subscribes to that Observable (vs initializing it in the service controller)

Here's the starting point, can't get it to work (see comment after this.getAirpotsFromDB() call) :

global-cache.service.ts

airports: BehaviorSubject<string[]> = new BehaviorSubject(null);
get airports$(): Observable<string[]> {
  if (this.airports.getValue() == null) {
    //get list from db, and initialize the subject
    this.getAirportsFromDB();
    //**PROBLEM:** how do I return `this.airports.asObservable()` after it's initialized with data from the call above or return it from inside the call?
  }
  else{
    //list initialized, emit from subject (don't hit db)
    return this.airports.asObservable();
  }
}

getAirportsFromDB() {
  this.http.get<string[]>('/api/airports').subscribe((_result) => {
    this.airports.next(_result);
  });
}

myComponent1.ts

//imports global-cache.service but never subscribes to airports$ (service has many other arrays that are used here)
//User lands here first, `getAirportsFromDB()` never gets called, user goes to myComponent2

myComponent2.ts

...
airports$: any = this.globalCacheService.airports$;
//subscribed in html `airports$ | async`
...
//user lands here, `getAirportsFromDB()` is called, `airports` BehaviorSubject is initialized
//user then goes to myComponent3

myComponent3.ts

...
airports$: any = this.globalCacheService.airports$;
//subscribed in html `airports$ | async`
...
//`airports` BehaviorSubject emits last value (initialized in Component2). `getAirportsFromDB()` does not get called again

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我的黑色迷你裙 2025-01-22 07:15:52

您可以尝试如下所示,只需使用 tap 运算符并将 http 请求的值保存在 BehaviorSubject 中,并从 getAirportsFromDB 返回 Observable

export class Service {

  airports: BehaviorSubject<string[]> = new BehaviorSubject(null);

  get airports$(): Observable<string[]> {
    return this.airports.getValue()
        ? this.airports.asObservable()
        : this.getAirportsFromDB();
  }

  getAirportsFromDB(): Observable<string[]> {
    return this.http.get<string[]>('/api/airports')
      .pipe(
        tap((_result) => this.airports.next(_result))
      )
  }
}

小更新:
第一次调用时不会返回BehaviorSubject observable,因此对 getter 的后续调用不会更新视图,因此您只能在将其用作缓存并且不想接收的情况下使用上面的代码任何更新

You can try something like below, just use tap operator and save the value of http request in the BehaviorSubject and return Observable from getAirportsFromDB

export class Service {

  airports: BehaviorSubject<string[]> = new BehaviorSubject(null);

  get airports$(): Observable<string[]> {
    return this.airports.getValue()
        ? this.airports.asObservable()
        : this.getAirportsFromDB();
  }

  getAirportsFromDB(): Observable<string[]> {
    return this.http.get<string[]>('/api/airports')
      .pipe(
        tap((_result) => this.airports.next(_result))
      )
  }
}

Minor update:
The BehaviorSubject observable isn't getting returned on the first call so subsequent calls to the getter wouldn't update the view, so you can use the code above only in case, that you use it as the cache and don't want to receive any updates

我ぃ本無心為│何有愛 2025-01-22 07:15:52

最终选择了 shareReplay(1);方法更简单,并且完全符合我的要求

global-cache.service.ts

airports$: Observable<string[]> = this.getAirportsFromDB();

getAirportsFromDB() {
  return this.http.get<string[]>('/api/airports').pipe(shareReplay(1));
}

Ended up going with shareReplay(1); way easier and does exactly what I wanted

global-cache.service.ts

airports$: Observable<string[]> = this.getAirportsFromDB();

getAirportsFromDB() {
  return this.http.get<string[]>('/api/airports').pipe(shareReplay(1));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文