Files
Picsur/frontend/src/app/routes/settings/users/settings-users.component.ts

75 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-03-19 23:08:20 +01:00
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { AutoUnsubscribe } from 'ngx-auto-unsubscribe-decorator';
import { EUser } from 'picsur-shared/dist/entities/user.entity';
import { HasFailed } from 'picsur-shared/dist/types';
import { BehaviorSubject, Subject, throttleTime } from 'rxjs';
2022-03-21 21:21:21 +01:00
import { SnackBarType } from 'src/app/models/snack-bar-type';
2022-03-19 23:08:20 +01:00
import { UserManageService } from 'src/app/services/api/usermanage.service';
2022-03-21 21:21:21 +01:00
import { UtilService } from 'src/app/util/util.service';
2022-03-19 21:34:33 +01:00
@Component({
templateUrl: './settings-users.component.html',
2022-03-19 23:08:20 +01:00
styleUrls: ['./settings-users.component.scss'],
2022-03-19 21:34:33 +01:00
})
export class SettingsUsersComponent implements OnInit {
2022-03-21 17:21:03 +01:00
public readonly displayedColumns: string[] = ['id', 'username', 'actions'];
2022-03-19 23:08:20 +01:00
public readonly pageSizeOptions: number[] = [5, 10, 25, 100];
public readonly startingPageSize = this.pageSizeOptions[2];
2022-03-19 21:34:33 +01:00
2022-03-19 23:08:20 +01:00
public dataSubject = new BehaviorSubject<EUser[]>([]);
public updateSubject = new Subject<PageEvent>();
@ViewChild(MatPaginator) paginator: MatPaginator;
2022-03-21 21:21:21 +01:00
constructor(
private userManageService: UserManageService,
private utilService: UtilService
) {}
2022-03-19 23:08:20 +01:00
async ngOnInit() {
this.subscribeToUpdate();
this.fetchUsers(this.startingPageSize, 0);
}
@AutoUnsubscribe()
private subscribeToUpdate() {
return this.updateSubject
.pipe(throttleTime(500, undefined, { leading: true, trailing: true }))
.subscribe(async (pageEvent: PageEvent) => {
2022-03-20 22:11:17 +01:00
let success = await this.fetchUsers(
2022-03-19 23:08:20 +01:00
pageEvent.pageSize,
pageEvent.pageIndex
);
2022-03-20 22:11:17 +01:00
if (!success) {
if (pageEvent.previousPageIndex === pageEvent.pageIndex - 1) {
2022-03-19 23:08:20 +01:00
this.paginator.previousPage();
} else {
this.paginator.firstPage();
}
}
});
2022-03-19 21:34:33 +01:00
}
2022-03-19 23:08:20 +01:00
private async fetchUsers(
pageSize: number,
pageIndex: number
2022-03-20 22:11:17 +01:00
): Promise<boolean> {
2022-03-19 23:08:20 +01:00
const result = await this.userManageService.getUsers(pageSize, pageIndex);
2022-03-21 21:21:21 +01:00
if (HasFailed(result)) {
this.utilService.showSnackBar(
'Failed to fetch users',
SnackBarType.Error
);
return false;
}
2022-03-19 23:08:20 +01:00
2022-03-20 22:11:17 +01:00
if (result.length > 0) {
this.dataSubject.next(result);
return true;
}
2022-03-19 23:08:20 +01:00
2022-03-20 22:11:17 +01:00
return false;
2022-03-19 23:08:20 +01:00
}
2022-03-19 21:34:33 +01:00
}