Thoker
Thoker

Reputation: 100

ngrx effects - Use a selector inside an effect after using a service

I need to make an API Call. I need to get some data from the store inside my effect. Already tried with withLatestForm but as fas as I understand you can only use it at the beginning. Help would be appreciated.

    sendTestStop = createEffect(() => {
        return this.actions$.pipe(
            ofType('[API] do it'),
            switchMap(() => this.RestApiService.DoCommand()),
            switchMap(
                    ((value: TestStopResponse) => {
                        let response = [];
                        for (const test of value.ResponseArray) {
                            // here i need some data from the store <-------------------------
                            if(test.IsStopped){
                                response.push(this.viewActions.action({logString: "logmsg"}));
                                response.push(this.activeTestActions.action2({test: test}));
                            }
                            else{
                                response.push(this.viewActions.addLogEntry({logString: "logmsg"}));
                            }

                        }
                        return response;

                    })),
            )
    });

Upvotes: 0

Views: 1106

Answers (2)

Priyamal
Priyamal

Reputation: 2969

you can use combineLatest operator.

sendTestStop = createEffect(() => {
    return this.actions$.pipe(
        ofType('[API] do it'),
        combineLatest(
        [withLatestFrom(this.store.pipe(select(yourSelector))),
          this.RestApiService.DoCommand()]),
        mergeMap(([action, storedata, apiData]) => { buisness logic here } )
  )};

Upvotes: 1

Thoker
Thoker

Reputation: 100

See the comments under @Priyamal answer to see, why this solution is correct for my case.

sendTestStop = createEffect(() => {
    return this.actions$.pipe(
        ofType('[API] do it'),
        mergeMap(() => this.RestApiService.DoCommand()),
        withLatestFrom(this.store.pipe(select(this.testSelector.selectAllTestSetsArray))),
        switchMap(
                ([apiValue, storeValue]) => {
                    let response = [];
                    for (const test of value.ResponseArray) {
                        // here i need some data from the store <-------------------------
                        if(test.IsStopped){
                            response.push(this.viewActions.action({logString: "logmsg"}));
                            response.push(this.activeTestActions.action2({test: test}));
                        }
                        else{
                            response.push(this.viewActions.addLogEntry({logString: "logmsg"}));
                        }

                    }
                    return response;

                })),
        )
});

Upvotes: 1

Related Questions