Darthg8r
Darthg8r

Reputation: 12675

NGRX Action that depends on other observable(selector) values

I've got a situation where I have 2 separate data sources that I need to fetch data from. One data source depends on 2 values that come from other values in the store.

In the code sample below, I need to fetch a list of "banks" and render them. Then at some point in the future, I need to "login" and fetch a list of "balances" for those banks.

I'm having trouble with the dependency part. I can subscribe to the observables manually and it works, but I don't think it's the right way. I suspect the right way is some combination of rxjs operators and selectors. I'd appreciate some direction.

Component

import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { getBalancesAction, getBanksAction, loginAction } from './store/app.actions';
import { selectBalances, selectBanks, selectLogin } from './store/app.selectors';
import { IAppState } from './store/app.state';
import * as _ from 'lodash';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit
{

    // Desired behavior
    // Banks render right off the bat.
    // CLicking login

    public banks$ = this.store.select(selectBanks);
    public login$ = this.store.select(selectLogin);
    public balances$ = this.store.select(selectBalances);

    constructor(private store: Store<IAppState>)
    {

    }

    ngOnInit()
    {
        this.store.dispatch(getBanksAction());

        // You can view the list of banks without being logged in
        // I need to call this.store.dispatch(getBalances(banks$, login$))
        // but only after I have a login and the list of banks.
        // I could subscribe, but that doesn't seem to be in the spirit of ngrx and rxjs.
        this.banks$.subscribe(banks =>
        {
            if (banks)
            {
                this.login$.subscribe(login =>
                {
                    if (login)
                    {
                        // getting balances requires the accountid and a list of banks.  These come from observables of their own.
                        this.store.dispatch(getBalancesAction({ accountId: login, banks: _.map(banks, b => b.id) }))
                    }
                })
            }
        });


    }

    public login(): void
    {
        this.store.dispatch(loginAction({ userName: 'justme' }));
    }
}

Actions

import { createAction, props } from "@ngrx/store";
import { IBalance, IBank } from "./app.state";

export enum BankActions
{
    GET_BANKS = "GET_BANKS",
    GET_BANKS_SUCCESS = "GET_BANKS_SUCCESS",
    GET_BALANCES = "GET_BALANCES",
    GET_BALANCE_SUCCESS = "GET_BALANCES_SUCCESS",
    LOGIN = "LOGIN",
    LOGIN_SUCCESS = "LOGIN_SUCCESS"
}

export const getBanksAction = createAction(
    BankActions.GET_BANKS
);

export const getBanksSuccessAction = createAction(BankActions.GET_BANKS_SUCCESS, props<{ banks: IBank[] }>());


export const getBalancesAction = createAction(
    BankActions.GET_BALANCES,
    props<{ accountId: string, banks: string[] }>()
);

export const getBalancesSuccessAction = createAction(BankActions.GET_BALANCE_SUCCESS, props<{ balances: IBalance[] }>());

export const loginAction = createAction(
    BankActions.LOGIN,
    props<{userName: string}>()
)

export const loginSuccessAction= createAction(
    BankActions.LOGIN_SUCCESS,
    props<{accountId: string}>()
)

effects

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { defer, forkJoin, from, of } from 'rxjs';
import { map, mergeMap, tap } from 'rxjs/operators';
import { BanksService } from '../banks.service';
import { BankActions, getBalancesSuccessAction, getBanksSuccessAction, loginSuccessAction } from './app.actions';

@Injectable()
export class BankEffects
{
    constructor(private actions$: Actions, private banksService: BanksService) { }

    loadBalances$ = createEffect(() => this.actions$.pipe(
        ofType(BankActions.GET_BALANCES),
        mergeMap((x:any) => this.banksService.getBalances(x.accountId, x.banks)
            .pipe(
                map(b => getBalancesSuccessAction({ balances: b }))
            ))
    )
    );

    loadBanks$ = createEffect(() => this.actions$.pipe(
        ofType(BankActions.GET_BANKS),
        mergeMap(() => this.banksService.getBanks()
            .pipe(
                map(b => getBanksSuccessAction({ banks: b }))
            ))
    )
    );

    doLogin$ = createEffect(() => this.actions$.pipe(
        ofType(BankActions.LOGIN),
        mergeMap((x) => this.banksService.login(x)
            .pipe(
                map(b => loginSuccessAction({ accountId: b }))
            ))
    )
    );
}

Reducers

import { createReducer, on } from "@ngrx/store";
import { getBalancesSuccessAction, loginSuccessAction, getBanksSuccessAction } from "./app.actions";
import { IAppState, initialState } from "./app.state";

export const appReducer = createReducer(
    initialState,
    on(getBalancesSuccessAction, (state: IAppState, { balances }) => ({ ...state, balances: balances })),
    on(loginSuccessAction, (state: IAppState, { accountId }) => ({ ...state, accountId: accountId })),
    on(getBanksSuccessAction, (state: IAppState, { banks }) =>
    {
        return ({ ...state, banks: banks });
    }));

Selectors

import { createSelector } from "@ngrx/store";
import { IAppState } from "./app.state";

export const selectFeature = (state: any) => state.app;

export const selectLogin = createSelector(
    selectFeature,
    (state: IAppState) => state.accountId
);

export const selectBanks = createSelector(
    selectFeature,
    (state: IAppState) =>
    {
        return state.banks;
    }
);

export const selectBalances = createSelector(
    selectFeature,
    (state: IAppState) => state.balances
);

State

export interface IBank
{
    id: string;
    name: string;
}

export interface IBalance{
    bankId: string,
    value: number;
    internalAccountNumber: string
}

export interface IAppState
{
    banks: IBank[],
    accountId: string | null,
    balances: IBalance[]
}

export const initialState: IAppState = {
    banks: [],
    accountId: null,
    balances: []
};

Upvotes: 2

Views: 2572

Answers (2)

wlf
wlf

Reputation: 3393

  1. Your ngOnInit should only dispatch BankActions.GET_BANKS. It should not contain any subscribes
  2. Use async pipe in template to subscribe to banks$ and balances$
  3. loadBalances$ should be triggered by BankActions.LOGIN_SUCCESS, you can get the account ID and banks list from the store within the effect using withLatestFrom (https://stackoverflow.com/a/60287236/1188074)
  4. Remove BankActions.GET_BALANCES
  5. Remove login$ from your component

References

Chaining Effects

Manual subscribes

Upvotes: 3

The Fabio
The Fabio

Reputation: 6240

You could use combineLatest, as it yields all Observable's values

Also, you don't need loadash for the map function.

combineLatest([this.banks$, this.login$])
    .pipe(
      // to prevent unwanted many yields on a short while
      debouncTime(50),
      // only yields when there are banks and the accountId is filled in.
      filter(([banks, accountId]) => banks?.length > 0 && accountId) 
    )
    .subscribe(([banks, accountId]) =>
      this.store.dispatch(getBalancesAction({ accountId, banks: banks.map(b => b.id) }))
    );

Upvotes: 0

Related Questions