base-report.component.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { MatDialog } from "@angular/material";
  2. import { Location } from '@angular/common';
  3. import { DataSource } from "@angular/cdk/collections";
  4. import { Observable } from "rxjs/Observable";
  5. import { BehaviorSubject } from "rxjs/BehaviorSubject";
  6. import { ReportDataService } from "./services/reportData.service";
  7. import { CreateReportItemDialogComponent } from "./create-report-item.component";
  8. import { ReportItem } from "./types";
  9. export abstract class BaseReportComponent {
  10. abstract title: string;
  11. description = '';
  12. dataSource: ReportItemsDataSource;
  13. displayedColumns = ['description', 'amount', 'type', 'date', 'hasReceipt'];
  14. protected itemsDataBase: ReportItemDatabase;
  15. constructor(protected location: Location,
  16. private dialog: MatDialog,
  17. protected reportDataService: ReportDataService) {
  18. this.itemsDataBase = new ReportItemDatabase();
  19. this.dataSource = new ReportItemsDataSource(this.itemsDataBase);
  20. }
  21. cancel(): void {
  22. this.location.back();
  23. }
  24. addItem(): void {
  25. const dialogRef = this.dialog.open(CreateReportItemDialogComponent, {
  26. width: '525px',
  27. });
  28. dialogRef.afterClosed().subscribe(item => {
  29. if (item) {
  30. this.itemsDataBase.addReportItem(item);
  31. }
  32. });
  33. }
  34. abstract save(): void;
  35. }
  36. class ReportItemDatabase {
  37. dataChange = new BehaviorSubject<ReportItem[]>([]);
  38. get data(): ReportItem[] {
  39. return this.dataChange.value;
  40. }
  41. addReportItem(item: ReportItem) {
  42. const newData = [...this.data, item];
  43. this.dataChange.next(newData);
  44. }
  45. addRange(items: ReportItem[]) {
  46. const newData = [...this.data, ...items];
  47. this.dataChange.next(newData);
  48. }
  49. }
  50. class ReportItemsDataSource extends DataSource<any> {
  51. constructor(private sourceDatabase: ReportItemDatabase) {
  52. super();
  53. }
  54. connect(): Observable<ReportItem[]> {
  55. return this.sourceDatabase.dataChange.map(data => data);
  56. }
  57. disconnect() { }
  58. }