]>
Commit | Line | Data |
---|---|---|
fd45e8f4 C |
1 | import { OnDestroy, OnInit } from '@angular/core' |
2 | import { ActivatedRoute, Router } from '@angular/router' | |
fd45e8f4 C |
3 | |
4 | import { NotificationsService } from 'angular2-notifications' | |
9bf9d2a5 C |
5 | import { Observable } from 'rxjs/Observable' |
6 | import { Subscription } from 'rxjs/Subscription' | |
fd45e8f4 | 7 | |
9bf9d2a5 | 8 | import { SortField, Video, VideoPagination } from '../../shared' |
fd45e8f4 C |
9 | |
10 | export abstract class AbstractVideoList implements OnInit, OnDestroy { | |
fd45e8f4 C |
11 | pagination: VideoPagination = { |
12 | currentPage: 1, | |
13 | itemsPerPage: 25, | |
14 | totalItems: null | |
15 | } | |
9bf9d2a5 | 16 | sort: SortField = '-createdAt' |
fd45e8f4 C |
17 | videos: Video[] = [] |
18 | ||
19 | protected notificationsService: NotificationsService | |
20 | protected router: Router | |
21 | protected route: ActivatedRoute | |
22 | ||
23 | protected subActivatedRoute: Subscription | |
24 | ||
9bf9d2a5 | 25 | abstract titlePage: string |
fd45e8f4 C |
26 | abstract getVideosObservable (): Observable<{ videos: Video[], totalVideos: number}> |
27 | ||
28 | ngOnInit () { | |
29 | // Subscribe to route changes | |
30 | this.subActivatedRoute = this.route.params.subscribe(routeParams => { | |
31 | this.loadRouteParams(routeParams) | |
32 | ||
33 | this.getVideos() | |
34 | }) | |
35 | } | |
36 | ||
37 | ngOnDestroy () { | |
38 | this.subActivatedRoute.unsubscribe() | |
39 | } | |
40 | ||
41 | getVideos () { | |
fd45e8f4 C |
42 | this.videos = [] |
43 | ||
44 | const observable = this.getVideosObservable() | |
45 | ||
46 | observable.subscribe( | |
47 | ({ videos, totalVideos }) => { | |
48 | this.videos = videos | |
49 | this.pagination.totalItems = totalVideos | |
fd45e8f4 C |
50 | }, |
51 | error => this.notificationsService.error('Error', error.text) | |
52 | ) | |
53 | } | |
54 | ||
fd45e8f4 C |
55 | onPageChanged (event: { page: number }) { |
56 | // Be sure the current page is set | |
57 | this.pagination.currentPage = event.page | |
58 | ||
59 | this.navigateToNewParams() | |
60 | } | |
61 | ||
fd45e8f4 C |
62 | protected buildRouteParams () { |
63 | // There is always a sort and a current page | |
64 | const params = { | |
65 | sort: this.sort, | |
66 | page: this.pagination.currentPage | |
67 | } | |
68 | ||
69 | return params | |
70 | } | |
71 | ||
72 | protected loadRouteParams (routeParams: { [ key: string ]: any }) { | |
73 | this.sort = routeParams['sort'] as SortField || '-createdAt' | |
74 | ||
75 | if (routeParams['page'] !== undefined) { | |
76 | this.pagination.currentPage = parseInt(routeParams['page'], 10) | |
77 | } else { | |
78 | this.pagination.currentPage = 1 | |
79 | } | |
80 | } | |
81 | ||
82 | protected navigateToNewParams () { | |
83 | const routeParams = this.buildRouteParams() | |
84 | this.router.navigate([ '/videos/list', routeParams ]) | |
85 | } | |
86 | } |