reduxjs / angular-redux

Official Angular bindings for Redux
MIT License
71 stars 7 forks source link

Injector demo #13

Closed crutchcorn closed 1 month ago

crutchcorn commented 1 month ago

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

netlify[bot] commented 1 month ago

Deploy Preview for angular-redux-docs canceled.

Name Link
Latest commit 66be8c7729dfdb83b6e23bd3bc8d0acb0ad1cc1a
Latest deploy log https://app.netlify.com/sites/angular-redux-docs/deploys/66f0dd695a61e9000886e258