import {Component, OnInit} from "@angular/core"; import {Location} from "@angular/common"; import {FormControl} from "@angular/forms"; import {ActivatedRoute, Router} from "@angular/router"; import {Observable} from "rxjs/Observable"; import {UserService} from "../../services/user-service/user.service"; import {User} from "../../models/model-interfaces"; import {ADD, LOAD} from "../../services/stores/user.store"; @Component({ selector: 'squad-list', templateUrl: './user-list.component.html', styleUrls: ['./user-list.component.css', '../../style/select-list.css'] }) export class UserListComponent implements OnInit { selectedUserId: string | number = null; users$: Observable; searchTerm = new FormControl(); public radioModel: string; throttle = 300; scrollDistance = 1; offset = 0; limit = 20; constructor(private userService: UserService, private router: Router, private route: ActivatedRoute, private location: Location) { } ngOnInit() { this.users$ = this.userService.users$; const paramsStream = this.route.queryParams .map(params => decodeURI(params['query'] || '')) .do(query => this.searchTerm.setValue(query)); const searchTermStream = this.searchTerm.valueChanges .debounceTime(400) .do(query => this.adjustBrowserUrl(query)); Observable.merge(paramsStream, searchTermStream) .distinctUntilChanged() .switchMap(query => this.filterUsers()) .subscribe(); } openNewUserForm() { this.selectedUserId = null; this.router.navigate([{outlets: {'right': ['new']}}], {relativeTo: this.route}); } selectUser(userId: string) { this.selectedUserId = userId; this.router.navigate([{outlets: {'right': ['edit', userId]}}], {relativeTo: this.route}); } awardUser(userId) { this.selectedUserId = userId; this.router.navigate([{outlets: {'right': ['award', userId]}}], {relativeTo: this.route}); } deleteUser(user: User) { if (confirm('Soll der Teilnehmer "' + user.username + '" wirklich gelöscht werden?')) { this.userService.deleteUser(user) .subscribe((res) => { }) } } filterUsers(action?) { if (!action || action === LOAD) { this.offset = 0; this.limit = 20; } return this.users$ = this.userService.findUsers(this.searchTerm.value, this.radioModel, null, this.limit, this.offset, action); } onScrollDown() { if (this.offset + this.limit > this.userService.totalCount) { this.limit = this.userService.totalCount - this.offset; } if (this.limit != 0) { this.offset += this.limit; this.filterUsers(ADD); } } adjustBrowserUrl(queryString = '') { const absoluteUrl = this.location.path().split('?')[0]; const queryPart = queryString !== '' ? `query=${queryString}` : ''; this.location.replaceState(absoluteUrl, queryPart); } }