]>
Commit | Line | Data |
---|---|---|
1 | import { Injectable } from '@angular/core' | |
2 | import { NavigationEnd, Router } from '@angular/router' | |
3 | import { ServerService } from '../server' | |
4 | ||
5 | @Injectable() | |
6 | export class RedirectService { | |
7 | // Default route could change according to the instance configuration | |
8 | static INIT_DEFAULT_ROUTE = '/videos/trending' | |
9 | static DEFAULT_ROUTE = RedirectService.INIT_DEFAULT_ROUTE | |
10 | ||
11 | private previousUrl: string | |
12 | private currentUrl: string | |
13 | ||
14 | constructor ( | |
15 | private router: Router, | |
16 | private serverService: ServerService | |
17 | ) { | |
18 | // The config is first loaded from the cache so try to get the default route | |
19 | const config = this.serverService.getConfig() | |
20 | if (config && config.instance && config.instance.defaultClientRoute) { | |
21 | RedirectService.DEFAULT_ROUTE = config.instance.defaultClientRoute | |
22 | } | |
23 | ||
24 | // Load default route | |
25 | this.serverService.configLoaded | |
26 | .subscribe(() => { | |
27 | const defaultRouteConfig = this.serverService.getConfig().instance.defaultClientRoute | |
28 | ||
29 | if (defaultRouteConfig) { | |
30 | RedirectService.DEFAULT_ROUTE = defaultRouteConfig | |
31 | } | |
32 | }) | |
33 | ||
34 | // Track previous url | |
35 | this.currentUrl = this.router.url | |
36 | router.events.subscribe(event => { | |
37 | if (event instanceof NavigationEnd) { | |
38 | this.previousUrl = this.currentUrl | |
39 | this.currentUrl = event.url | |
40 | } | |
41 | }) | |
42 | } | |
43 | ||
44 | redirectToPreviousRoute () { | |
45 | if (this.previousUrl) return this.router.navigateByUrl(this.previousUrl) | |
46 | ||
47 | return this.redirectToHomepage() | |
48 | } | |
49 | ||
50 | redirectToHomepage (skipLocationChange = false) { | |
51 | console.log('Redirecting to %s...', RedirectService.DEFAULT_ROUTE) | |
52 | ||
53 | this.router.navigate([ RedirectService.DEFAULT_ROUTE ], { skipLocationChange }) | |
54 | .catch(() => { | |
55 | console.error( | |
56 | 'Cannot navigate to %s, resetting default route to %s.', | |
57 | RedirectService.DEFAULT_ROUTE, | |
58 | RedirectService.INIT_DEFAULT_ROUTE | |
59 | ) | |
60 | ||
61 | RedirectService.DEFAULT_ROUTE = RedirectService.INIT_DEFAULT_ROUTE | |
62 | return this.router.navigate([ RedirectService.DEFAULT_ROUTE ], { skipLocationChange }) | |
63 | }) | |
64 | ||
65 | } | |
66 | } |