简体   繁体   English

你如何结合 RxJs 和 NgRx 来进行多个 Rest-Call 并让它们等待结果?

[英]How do you combine RxJs and NgRx to make multiple Rest-Calls and make them wait for a result?

In my Effect im listening on an Action, that value of the Action is a string Array.在我的 Effect 中,我正在监听一个 Action,该 Action 的值是一个字符串数组。 Now i need to loop over the array and use the values as inputs for the next asnyc function.现在我需要遍历数组并将这些值用作下一个 asnyc function 的输入。

someEffect$ = createEffect(() => 
    this.action$.pipe(
        ofType(someAction),
        mergeMap(({ someValue }) => 
            this.httpCall.getSomeTh(someValue[0]).pipe(
                map((result) => someOtherAction)
            )
        )       
    )
)

I have tried a few different things.我尝试了一些不同的东西。 The one below seemed to get me to the closest one i wanted.下面的那个似乎让我找到了我想要的最接近的那个。 But since the Rest-calls need a moment to return, the array is always empty.但是由于 Rest-calls 需要一段时间才能返回,所以数组总是空的。

someEffect$ = createEffect(() => 
    this.action$.pipe(
        ofType(someAction),
        mergeMap(({ someValue }) => {
              const array = [];
              someValue.forEach((value) => 
                 this.http.get(value).pipe(tap((object) => array.push(object)))
              )

              return of(someOtherAction(array))
            }
        )       
    )
)

Does anyone have an idea, how to make the whole thing wait for the rest calls to return back?有谁知道如何让整个事情等待 rest 电话返回?

Use a forkJoin .使用forkJoin

someEffect$ = createEffect(() => 
    this.action$.pipe(
        ofType(someAction),
        mergeMap(({ someValue }) => 
          forkJoin(someValue.map(value => this.http.get(value)))              
        )       
    )
)

The forkJoin takes an array of Obserables and emits when every Observable is completed. forkJoin接受一个 Obserables 数组,并在每个 Observable 完成时发出。 It outputs the results as an array.它将结果输出为数组。

Simply you can continue writing the next call after you finished the first one (someValue.forEach).您只需在完成第一个调用 (someValue.forEach) 后继续编写下一个调用。

The long scenario is:长期的情况是:

  1. Call the action "someOtherAction".将操作称为“someOtherAction”。
  2. Create a Reducer that reads the array and update the Store with it.创建一个读取数组并用它更新 Store 的 Reducer。
  3. Create a Selector that reads the array from the Store.创建一个从存储中读取数组的选择器。
  4. In the Component you subscribe on the Selector.在您订阅选择器的组件中。
  5. Inside the Subscribe event you Dispatch a new Action that call the second call you mentioned.在 Subscribe 事件中,您 Dispatch 一个新的 Action 调用您提到的第二个调用。 For inspiration, you can read this example in gitHub: https://github.com/DeborahK/Angular-NgRx-GettingStarted/tree/master/APM-Demo5/src/app/products/state为了获得灵感,您可以阅读 gitHub 中的这个示例: https://github.com/DeborahK/Angular-NgRx-GettingStarted/tree/master/APM-Demo5/src/app/products/state

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM