File tree Expand file tree Collapse file tree 2 files changed +34
-26
lines changed
projects/angular-redux-injector-demo/src/app Expand file tree Collapse file tree 2 files changed +34
-26
lines changed Original file line number Diff line number Diff line change 1
1
import { createAsyncThunk , createSlice } from '@reduxjs/toolkit' ;
2
- import {
3
- EnvironmentInjector ,
4
- inject ,
5
- runInInjectionContext ,
6
- } from '@angular/core' ;
2
+ import { inject } from '@angular/core' ;
7
3
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' ;
12
8
13
9
export const incrementByRandomNumber = createAsyncThunk (
14
10
'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 ;
32
16
} ) ;
33
17
} ,
34
18
) ;
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments