-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
router_store_module.ts
346 lines (311 loc) · 8.89 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import {
Inject,
InjectionToken,
ModuleWithProviders,
NgModule,
} from '@angular/core';
import {
NavigationCancel,
NavigationError,
NavigationEnd,
Router,
RouterStateSnapshot,
RoutesRecognized,
Event,
NavigationStart,
} from '@angular/router';
import { select, Store } from '@ngrx/store';
import { of } from 'rxjs';
import {
DefaultRouterStateSerializer,
RouterStateSerializer,
SerializedRouterStateSnapshot,
} from './serializer';
/**
* An action dispatched when the router navigates.
*/
export const ROUTER_NAVIGATION = 'ROUTER_NAVIGATION';
/**
* Payload of ROUTER_NAVIGATION.
*/
export type RouterNavigationPayload<T> = {
routerState: T;
event: RoutesRecognized;
};
/**
* An action dispatched when the router navigates.
*/
export type RouterNavigationAction<T = SerializedRouterStateSnapshot> = {
type: typeof ROUTER_NAVIGATION;
payload: RouterNavigationPayload<T>;
};
/**
* An action dispatched when the router cancels navigation.
*/
export const ROUTER_CANCEL = 'ROUTER_CANCEL';
/**
* Payload of ROUTER_CANCEL.
*/
export type RouterCancelPayload<T, V> = {
routerState: V;
storeState: T;
event: NavigationCancel;
};
/**
* An action dispatched when the router cancel navigation.
*/
export type RouterCancelAction<T, V = SerializedRouterStateSnapshot> = {
type: typeof ROUTER_CANCEL;
payload: RouterCancelPayload<T, V>;
};
/**
* An action dispatched when the router errors.
*/
export const ROUTER_ERROR = 'ROUTE_ERROR';
/**
* Payload of ROUTER_ERROR.
*/
export type RouterErrorPayload<T, V> = {
routerState: V;
storeState: T;
event: NavigationError;
};
/**
* An action dispatched when the router errors.
*/
export type RouterErrorAction<T, V = SerializedRouterStateSnapshot> = {
type: typeof ROUTER_ERROR;
payload: RouterErrorPayload<T, V>;
};
/**
* An union type of router actions.
*/
export type RouterAction<T, V = SerializedRouterStateSnapshot> =
| RouterNavigationAction<V>
| RouterCancelAction<T, V>
| RouterErrorAction<T, V>;
export type RouterReducerState<T = SerializedRouterStateSnapshot> = {
state: T;
navigationId: number;
};
export function routerReducer<T = SerializedRouterStateSnapshot>(
state: RouterReducerState<T> | undefined,
action: RouterAction<any, T>
): RouterReducerState<T> {
switch (action.type) {
case ROUTER_NAVIGATION:
case ROUTER_ERROR:
case ROUTER_CANCEL:
return {
state: action.payload.routerState,
navigationId: action.payload.event.id,
};
default:
return state as RouterReducerState<T>;
}
}
export interface StoreRouterConfig {
stateKey?: string;
}
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 = 'routerReducer';
export function _createDefaultRouterConfig(
config: StoreRouterConfig | StoreRouterConfigFunction
): StoreRouterConfig {
let _config: StoreRouterConfig;
if (typeof config === 'function') {
_config = config();
} else {
_config = config || {};
}
return {
stateKey: DEFAULT_ROUTER_FEATURENAME,
..._config,
};
}
export type StoreRouterConfigFunction = () => StoreRouterConfig;
/**
* 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: RouterStateSerializer, useClass: DefaultRouterStateSerializer },
{
provide: _ROUTER_CONFIG,
useValue: { stateKey: DEFAULT_ROUTER_FEATURENAME },
},
{
provide: ROUTER_CONFIG,
useFactory: _createDefaultRouterConfig,
deps: [_ROUTER_CONFIG],
},
],
})
export class StoreRouterConnectingModule {
static forRoot(
config?: StoreRouterConfig | StoreRouterConfigFunction
): ModuleWithProviders;
static forRoot(
config: StoreRouterConfig | StoreRouterConfigFunction = {}
): ModuleWithProviders {
return {
ngModule: StoreRouterConnectingModule,
providers: [
{ provide: _ROUTER_CONFIG, useValue: config },
{
provide: ROUTER_CONFIG,
useFactory: _createDefaultRouterConfig,
deps: [_ROUTER_CONFIG],
},
],
};
}
private lastEvent: Event | null = null;
private routerState: SerializedRouterStateSnapshot;
private storeState: any;
private lastRoutesRecognized: RoutesRecognized;
private dispatchTriggeredByRouter: boolean = false; // used only in dev mode in combination with routerReducer
private navigationTriggeredByDispatch: boolean = false; // used only in dev mode in combination with routerReducer
private stateKey: string;
constructor(
private store: Store<any>,
private router: Router,
private serializer: RouterStateSerializer<SerializedRouterStateSnapshot>,
@Inject(ROUTER_CONFIG) private config: StoreRouterConfig
) {
this.stateKey = this.config.stateKey as string;
this.setUpBeforePreactivationHook();
this.setUpStoreStateListener();
this.setUpStateRollbackEvents();
}
private setUpBeforePreactivationHook(): void {
(<any>this.router).hooks.beforePreactivation = (
routerState: RouterStateSnapshot
) => {
this.routerState = this.serializer.serialize(routerState);
if (this.shouldDispatchRouterNavigation()) {
this.dispatchRouterNavigation();
}
return of(true);
};
}
private setUpStoreStateListener(): void {
this.store.subscribe(s => {
this.storeState = s;
});
this.store.pipe(select(this.stateKey)).subscribe(() => {
this.navigateIfNeeded();
});
}
private shouldDispatchRouterNavigation(): boolean {
if (this.lastEvent instanceof NavigationStart) return false;
if (!this.storeState[this.stateKey]) return true;
return !this.navigationTriggeredByDispatch;
}
private navigateIfNeeded(): void {
if (
!this.storeState[this.stateKey] ||
!this.storeState[this.stateKey].state
) {
return;
}
if (this.dispatchTriggeredByRouter) return;
if (this.router.url !== this.storeState[this.stateKey].state.url) {
this.navigationTriggeredByDispatch = true;
this.router.navigateByUrl(this.storeState[this.stateKey].state.url);
}
}
private setUpStateRollbackEvents(): void {
this.router.events.subscribe(e => {
this.lastEvent = e;
if (e instanceof RoutesRecognized) {
this.lastRoutesRecognized = e;
} else if (e instanceof NavigationCancel) {
this.dispatchRouterCancel(e);
} else if (e instanceof NavigationError) {
this.dispatchRouterError(e);
} else if (e instanceof NavigationEnd) {
this.dispatchTriggeredByRouter = false;
this.navigationTriggeredByDispatch = false;
}
});
}
private dispatchRouterNavigation(): void {
this.dispatchRouterAction(ROUTER_NAVIGATION, {
routerState: this.routerState,
event: new RoutesRecognized(
this.lastRoutesRecognized.id,
this.lastRoutesRecognized.url,
this.lastRoutesRecognized.urlAfterRedirects,
this.routerState
),
});
}
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 dispatchRouterAction(type: string, payload: any): void {
this.dispatchTriggeredByRouter = true;
try {
this.store.dispatch({ type, payload });
} finally {
this.dispatchTriggeredByRouter = false;
this.navigationTriggeredByDispatch = false;
}
}
}