首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用rxjs管理API数据响应并管理应用程序状态-角10

使用rxjs管理API数据响应并管理应用程序状态-角10
EN

Stack Overflow用户
提问于 2020-08-12 10:22:29
回答 2查看 547关注 0票数 1

我试图了解从api存储(和更新)数据的最佳方法,并在兄弟组件之间共享这些数据。这就是我试过的。

拯救可观测的

代码语言:javascript
复制
export class MyExampleService {
   private data: Observable<any>;

   constructor(private readonly http: HttpClient) { }

   getData(): Observable<string[]> {
       //if we already got the data, just return that
       if (data) {
           return data;
       }

       //if not, get the data
       return this.http.get<string[]>('http://my-api.com/get-stuff')
           .pipe(tap((returnedData: string[]) => {
               //save the returned data so we can re-use it later without making more HTTP calls
               this.data= returnedData;
           }));
   }
}

但是这种方法并不完全符合我的需要,因为它不使用任何主题,当数据发生变化时,我想告诉我的其他组件。

使用主题

代码语言:javascript
复制
export class MyExampleService {
   private dataSbj: BehaviorSubject<any> = new BehaviorSubject(null);
   
   readonly data$ = this.dataSbj.asObservable();

   constructor(private readonly http: HttpClient) { }

   getData(): Observable<string[]> {

       if (dataSbj.getValue() === null) {
           return this.http.get<string[]>('http://my-api.com/get-stuff')
           .pipe(tap((returnedData: string[]) => {
               //save the returned data so we can re-use it later without making more HTTP calls
               this.dataSbj.next(returnedData);
           }));
       }          
   }
}

然后,我只需第一次订阅getData,并订阅所有其他组件中可观察到的数据$。(在本例中,我有一个父组件和多个子路由,因此我将在父组件中订阅getData(),并在所有子路由中订阅数据$)。

最后一种方法可以工作,但我宁愿使用相同的函数来检索相同的数据,而不是订阅不同的可观测值。

这是一个很好的方法,还是有什么更好的方法我可以做呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-08-12 10:31:06

如果您的getData()方法没有参数,您应该能够使用shareReplay()运算符执行以下操作。它只在第一个使用者订阅API时调用API,并将最后一个发出返回到任何顺序调用。这还包括更新数据的一种方法:

代码语言:javascript
复制
@Injectable({
  providedIn: 'root'
})
export class ExampleService {
  private updateData$ = new BehaviorSubject<void>(void 0); 

  readonly data$ = this.updateData$.pipe(
    switchMap(() => this.http.get('https://reqres.in/api/users')),
    shareReplay(1)
  );

  constructor(private readonly http: HttpClient) {}
   
  refresh(): void {
    this.updateData$.next();
  }
}
代码语言:javascript
复制
export class ExampleComponent {
  data$: Observable<any>;

  constructor(private example: ExampleService) {}

  getApi(): void {
    this.data$ = this.example.data$;
  }

  refresh(): void {
    this.example.refresh();
  }
}

工作实例检查控制台日志

票数 0
EN

Stack Overflow用户

发布于 2020-08-12 10:36:26

如果数据可用,NGRX商店状态管理是从存储中读取数据的方法,而不是进行不必要的网络调用。

通过发送相关操作,负责创建、更新和删除存储记录。

下面是github上使用ngrx存储的完整源代码演示

我强烈建议使用ngrx商店,它有一些很酷的功能,以避免不必要的网络调用,这导致了你的应用程序的速度加快。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63374542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档