Closed crutchcorn closed 1 month ago
This PR adds an example of how to add support for injecting services and such in an async thunk reducer.
inject
@Component({ selector: 'app-root', standalone: true, // ... }) export class AppComponent { injector = inject(EnvironmentInjector); dispatch = injectDispatch<AppDispatch>(); incrementByRandomNumber = () => { this.dispatch(incrementByRandomNumber({ injector: this.injector })); }; // ... }
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'; import { inject } from '@angular/core'; import { RandomNumberService } from '../services/random-number.service'; import { asyncRunInInjectionContext, RunInInjectionContextProps, } from '../utils/async-run-in-injection-context'; export const incrementByRandomNumber = createAsyncThunk( 'counter/incrementByAmountFromService', (arg: RunInInjectionContextProps<{}>, _thunkAPI) => { return asyncRunInInjectionContext(arg.injector, async () => { const service = inject(RandomNumberService); const newCount = await service.getRandomNumber(); return newCount; }); }, );
Where asyncRunInInjectionContext is provided as a small in-house utility:
asyncRunInInjectionContext
import { EnvironmentInjector, runInInjectionContext } from '@angular/core'; export const asyncRunInInjectionContext = <TReturn>( injector: EnvironmentInjector, fn: () => Promise<TReturn>, ) => { return new Promise<TReturn>((resolve, reject) => { runInInjectionContext(injector, () => { fn() .then((value) => { resolve(value); }) .catch((error) => { reject(error); }); }); }); }; export type RunInInjectionContextProps< T extends object, > = T & { injector: EnvironmentInjector; };
Addresses #12
This PR adds an example of how to add support for
inject
ing services and such in an async thunk reducer.Where
asyncRunInInjectionContext
is provided as a small in-house utility:Addresses #12