-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathrouter_store_module.ts
309 lines (283 loc) · 8.29 KB
/
router_store_module.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import {
Inject,
InjectionToken,
ModuleWithProviders,
NgModule,
ErrorHandler,
} from '@angular/core';
import {
NavigationCancel,
NavigationError,
NavigationEnd,
Router,
RoutesRecognized,
NavigationStart,
Event,
} from '@angular/router';
import { select, Selector, Store } from '@ngrx/store';
import { withLatestFrom } from 'rxjs/operators';
import {
ROUTER_CANCEL,
ROUTER_ERROR,
ROUTER_NAVIGATED,
ROUTER_NAVIGATION,
ROUTER_REQUEST,
} from './actions';
import { RouterReducerState } from './reducer';
import {
DefaultRouterStateSerializer,
RouterStateSerializer,
SerializedRouterStateSnapshot,
} from './serializer';
export type StateKeyOrSelector = string | Selector<any, RouterReducerState>;
export interface StoreRouterConfig {
stateKey?: StateKeyOrSelector;
serializer?: new (...args: any[]) => RouterStateSerializer;
/**
* By default, ROUTER_NAVIGATION is dispatched before guards and resolvers run.
* Therefore, the action could run too soon, for example
* there may be a navigation cancel due to a guard saying the navigation is not allowed.
* To run ROUTER_NAVIGATION after guards and resolvers,
* set this property to NavigationActionTiming.PostActivation.
*/
navigationActionTiming?: NavigationActionTiming;
}
export enum NavigationActionTiming {
PreActivation = 1,
PostActivation = 2,
}
export const _ROUTER_CONFIG = new InjectionToken(
'@ngrx/router-store Internal Configuration'
);
export const ROUTER_CONFIG = new InjectionToken(
'@ngrx/router-store Configuration'
);
export const DEFAULT_ROUTER_FEATURENAME = 'router';
export function _createRouterConfig(
config: StoreRouterConfig
): StoreRouterConfig {
return {
stateKey: DEFAULT_ROUTER_FEATURENAME,
serializer: DefaultRouterStateSerializer,
navigationActionTiming: NavigationActionTiming.PreActivation,
...config,
};
}
enum RouterTrigger {
NONE = 1,
ROUTER = 2,
STORE = 3,
}
/**
* Connects RouterModule with StoreModule.
*
* During the navigation, before any guards or resolvers run, the router will dispatch
* a ROUTER_NAVIGATION action, which has the following signature:
*
* ```
* export type RouterNavigationPayload = {
* routerState: SerializedRouterStateSnapshot,
* event: RoutesRecognized
* }
* ```
*
* Either a reducer or an effect can be invoked in response to this action.
* If the invoked reducer throws, the navigation will be canceled.
*
* If navigation gets canceled because of a guard, a ROUTER_CANCEL action will be
* dispatched. If navigation results in an error, a ROUTER_ERROR action will be dispatched.
*
* Both ROUTER_CANCEL and ROUTER_ERROR contain the store state before the navigation
* which can be used to restore the consistency of the store.
*
* Usage:
*
* ```typescript
* @NgModule({
* declarations: [AppCmp, SimpleCmp],
* imports: [
* BrowserModule,
* StoreModule.forRoot(mapOfReducers),
* RouterModule.forRoot([
* { path: '', component: SimpleCmp },
* { path: 'next', component: SimpleCmp }
* ]),
* StoreRouterConnectingModule
* ],
* bootstrap: [AppCmp]
* })
* export class AppModule {
* }
* ```
*/
@NgModule({
providers: [
{
provide: _ROUTER_CONFIG,
useValue: {},
},
{
provide: ROUTER_CONFIG,
useFactory: _createRouterConfig,
deps: [_ROUTER_CONFIG],
},
{
provide: RouterStateSerializer,
useClass: DefaultRouterStateSerializer,
},
],
})
export class StoreRouterConnectingModule {
static forRoot(
config: StoreRouterConfig = {}
): ModuleWithProviders<StoreRouterConnectingModule> {
return {
ngModule: StoreRouterConnectingModule,
providers: [
{ provide: _ROUTER_CONFIG, useValue: config },
{
provide: RouterStateSerializer,
useClass: config.serializer
? config.serializer
: DefaultRouterStateSerializer,
},
],
};
}
private lastEvent: Event | null = null;
private routerState: SerializedRouterStateSnapshot | null;
private storeState: any;
private trigger = RouterTrigger.NONE;
private stateKey: StateKeyOrSelector;
constructor(
private store: Store<any>,
private router: Router,
private serializer: RouterStateSerializer<SerializedRouterStateSnapshot>,
private errorHandler: ErrorHandler,
@Inject(ROUTER_CONFIG) private config: StoreRouterConfig
) {
this.stateKey = this.config.stateKey as StateKeyOrSelector;
this.setUpStoreStateListener();
this.setUpRouterEventsListener();
}
private setUpStoreStateListener(): void {
this.store
.pipe(
select(this.stateKey),
withLatestFrom(this.store)
)
.subscribe(([routerStoreState, storeState]) => {
this.navigateIfNeeded(routerStoreState, storeState);
});
}
private navigateIfNeeded(
routerStoreState: RouterReducerState,
storeState: any
): void {
if (!routerStoreState || !routerStoreState.state) {
return;
}
if (this.trigger === RouterTrigger.ROUTER) {
return;
}
if (this.lastEvent instanceof NavigationStart) {
return;
}
const url = routerStoreState.state.url;
if (this.router.url !== url) {
this.storeState = storeState;
this.trigger = RouterTrigger.STORE;
this.router.navigateByUrl(url).catch(error => {
this.errorHandler.handleError(error);
});
}
}
private setUpRouterEventsListener(): void {
const dispatchNavLate =
this.config.navigationActionTiming ===
NavigationActionTiming.PostActivation;
let routesRecognized: RoutesRecognized;
this.router.events
.pipe(withLatestFrom(this.store))
.subscribe(([event, storeState]) => {
this.lastEvent = event;
if (event instanceof NavigationStart) {
this.routerState = this.serializer.serialize(
this.router.routerState.snapshot
);
if (this.trigger !== RouterTrigger.STORE) {
this.storeState = storeState;
this.dispatchRouterRequest(event);
}
} else if (event instanceof RoutesRecognized) {
routesRecognized = event;
if (!dispatchNavLate && this.trigger !== RouterTrigger.STORE) {
this.dispatchRouterNavigation(event);
}
} else if (event instanceof NavigationCancel) {
this.dispatchRouterCancel(event);
this.reset();
} else if (event instanceof NavigationError) {
this.dispatchRouterError(event);
this.reset();
} else if (event instanceof NavigationEnd) {
if (this.trigger !== RouterTrigger.STORE) {
if (dispatchNavLate) {
this.dispatchRouterNavigation(routesRecognized);
}
this.dispatchRouterNavigated(event);
}
this.reset();
}
});
}
private dispatchRouterRequest(event: NavigationStart): void {
this.dispatchRouterAction(ROUTER_REQUEST, { event });
}
private dispatchRouterNavigation(
lastRoutesRecognized: RoutesRecognized
): void {
const nextRouterState = this.serializer.serialize(
lastRoutesRecognized.state
);
this.dispatchRouterAction(ROUTER_NAVIGATION, {
routerState: nextRouterState,
event: new RoutesRecognized(
lastRoutesRecognized.id,
lastRoutesRecognized.url,
lastRoutesRecognized.urlAfterRedirects,
nextRouterState
),
});
}
private dispatchRouterCancel(event: NavigationCancel): void {
this.dispatchRouterAction(ROUTER_CANCEL, {
routerState: this.routerState!,
storeState: this.storeState,
event,
});
}
private dispatchRouterError(event: NavigationError): void {
this.dispatchRouterAction(ROUTER_ERROR, {
routerState: this.routerState!,
storeState: this.storeState,
event: new NavigationError(event.id, event.url, `${event}`),
});
}
private dispatchRouterNavigated(event: NavigationEnd): void {
this.dispatchRouterAction(ROUTER_NAVIGATED, { event });
}
private dispatchRouterAction(type: string, payload: any): void {
this.trigger = RouterTrigger.ROUTER;
try {
this.store.dispatch({ type, payload });
} finally {
this.trigger = RouterTrigger.NONE;
}
}
private reset() {
this.trigger = RouterTrigger.NONE;
this.storeState = null;
this.routerState = null;
}
}