Skip to content

Conversation

crutchcorn
Copy link
Member

@crutchcorn crutchcorn commented Sep 23, 2024

This PR adds an example of how to add support for injecting services and such in an async thunk reducer.

@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:

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

Copy link

netlify bot commented Sep 23, 2024

Deploy Preview for angular-redux-docs canceled.

Name Link
🔨 Latest commit 66be8c7
🔍 Latest deploy log https://app.netlify.com/sites/angular-redux-docs/deploys/66f0dd695a61e9000886e258
@crutchcorn crutchcorn merged commit 0fbe8f3 into main Sep 23, 2024
6 checks passed
@aryaemami59 aryaemami59 deleted the injector-demo branch January 3, 2025 07:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant