Skip to content

Commit b547149

Browse files
committed
chore: refactors to make things a little nicer
1 parent d383822 commit b547149

File tree

2 files changed

+34
-26
lines changed

2 files changed

+34
-26
lines changed

projects/angular-redux-injector-demo/src/app/store/counter-slice.ts

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,18 @@
11
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
2-
import {
3-
EnvironmentInjector,
4-
inject,
5-
runInInjectionContext,
6-
} from '@angular/core';
2+
import { inject } from '@angular/core';
73
import { RandomNumberService } from '../services/random-number.service';
8-
9-
interface IncrementByAmountFromServiceProps {
10-
injector: EnvironmentInjector;
11-
}
4+
import {
5+
asyncRunInInjectionContext,
6+
RunInInjectionContextProps,
7+
} from '../utils/async-run-in-injection-context';
128

139
export const incrementByRandomNumber = createAsyncThunk(
1410
'counter/incrementByAmountFromService',
15-
(arg: IncrementByAmountFromServiceProps, _thunkAPI) => {
16-
return new Promise<number>((resolve, reject) => {
17-
runInInjectionContext(arg.injector, () => {
18-
const runValue = async () => {
19-
const service = inject(RandomNumberService);
20-
const newCount = await service.getRandomNumber();
21-
return newCount;
22-
};
23-
24-
runValue()
25-
.then((value) => {
26-
resolve(value);
27-
})
28-
.catch((error) => {
29-
reject(error);
30-
});
31-
});
11+
(arg: RunInInjectionContextProps<{}>, _thunkAPI) => {
12+
return asyncRunInInjectionContext(arg.injector, async () => {
13+
const service = inject(RandomNumberService);
14+
const newCount = await service.getRandomNumber();
15+
return newCount;
3216
});
3317
},
3418
);
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { EnvironmentInjector, runInInjectionContext } from '@angular/core';
2+
3+
export const asyncRunInInjectionContext = <TReturn>(
4+
injector: EnvironmentInjector,
5+
fn: () => Promise<TReturn>,
6+
) => {
7+
return new Promise<TReturn>((resolve, reject) => {
8+
runInInjectionContext(injector, () => {
9+
fn()
10+
.then((value) => {
11+
resolve(value);
12+
})
13+
.catch((error) => {
14+
reject(error);
15+
});
16+
});
17+
});
18+
};
19+
20+
export type RunInInjectionContextProps<
21+
T extends object,
22+
> = T & {
23+
injector: EnvironmentInjector;
24+
};

0 commit comments

Comments
 (0)