【问题标题】:Call function after getting data from RxJS store in angular 11从角度 11 中的 RxJS 存储获取数据后调用函数
【发布时间】:2021-05-20 23:58:42
【问题描述】:

我有一个 Angular 11 应用程序,它将各种数据保存在 RxJS 存储中。当组件需要访问该数据时,它会这样调用它:

this.store.select('myStore').subscribe(t => {
  this.array1 = t.array1;
  this.array2 = t.array2;
  this.array3 = t.array3;
  this.formData = t.myForm;
});

最后一条信息是存储形式。它只包含一堆值:

export interface IOpportunitySearch {
  fromDate: Date,
  toDate: Date,
  selectedUserIds: number[],
  ...
  userName: string
}

我想要做的是,当 myForm 数据从存储中返回时,设置一个回调来填充此组件中的表单。

有什么方法可以在检索到数据后触发填充表单?

有一个函数可以使用加载后我需要运行的数据进行 API 调用。该函数使用存储中的数据进行 api 调用:

updateData(form: IOpportunitySearch){
  ...
  this.storeService.onSetAllOpportunitiesSearch(form);  //this sets the store with the user's selected properties
  this.dataService.searchOpportunities(form).subscribe(data => {

所以当组件最初加载时,包括来自商店的表单数据,我想调用这个 updateData 方法。

【问题讨论】:

  • 这里有什么问题?为什么不能在 subscribe() 方法中这样做?
  • 加载数据后,我想使用该数据进行后续的 ajax 调用。它加载了我想发送到 api 的各种搜索参数
  • 有几种方法可以做到这一点,您应该为您的问题添加更多详细信息。您可以直接从subscribe 回调中进行调用,或者(更好地)使用 RxJS 运算符链接您的 http 调用。 You can easily find several answers on SO about that
  • 使用switchMap 运算符的示例:callApiOne().pipe(switchMap(dataFromApiOne => {return callApiTwo(dataFromApiOne);})).subscribe(dataFromApiTwo => {...})
  • 但是按照示例,这也适用于 rxjs 商店吗?

标签: angular rxjs


【解决方案1】:

因此,当您从商店接收数据时,您需要触发 http 调用吗?在这种情况下,不要直接订阅商店。添加一个高阶 observable 并订阅它。类似于以下示例:

在您的 service.ts 中:

readonly formDataFromApi$ = this.store.select('myStore').pipe(
  switchMap((t: any) => {
    // use the t.myForm here
    return this.http.get('someapi.endpoint.com');
  })
);

订阅组件中的 formDataFromApi$ observable。因此,每次您的商店数据发生变化时,它都会使用新数据触发一个新的 http 调用。

【讨论】:

  • 谢谢,但我收到此错误:'(t: any) => void' 类型的参数不可分配给 '(value: any, index: number) => ObservableInput'。类型 'void' 不可分配给类型 'ObservableInput'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 1970-01-01
相关资源
最近更新 更多