Self hosted FLOSS fitness/workout, nutrition and weight tracker
Correctly update UI when the list of entries changes
Roland Geider7b313a7a943d
diff --git a/angular/src/app/weight/models/weight.model.ts b/angular/src/app/weight/models/weight.model.tsindex c6dce428e..793dfe967 100644--- a/angular/src/app/weight/models/weight.model.ts+++ b/angular/src/app/weight/models/weight.model.ts@@ -35,7 +35,7 @@ export class WeightAdapter implements Adapter<WeightEntry> {fromJson(item: any): WeightEntry {return new WeightEntry(new Date(item.date),- item.weight,+ parseFloat(item.weight),item.id,);}diff --git a/angular/src/app/weight/weight-chart/weight-chart.component.html b/angular/src/app/weight/weight-chart/weight-chart.component.htmlindex 1a5411df2..6a5b10ea2 100644--- a/angular/src/app/weight/weight-chart/weight-chart.component.html+++ b/angular/src/app/weight/weight-chart/weight-chart.component.html@@ -1,5 +1,7 @@<ngx-charts-line-chart+ *ngIf="data !== null"+[view]="view"[scheme]="colorScheme"[legend]="legend"diff --git a/angular/src/app/weight/weight-chart/weight-chart.component.ts b/angular/src/app/weight/weight-chart/weight-chart.component.tsindex f6394fec4..81259bc35 100644--- a/angular/src/app/weight/weight-chart/weight-chart.component.ts+++ b/angular/src/app/weight/weight-chart/weight-chart.component.ts@@ -1,4 +1,5 @@-import {Component, OnInit, ViewChild} from '@angular/core';+import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core';+import {Subscription} from 'rxjs';import {WeightEntry} from '../models/weight.model';import {WeightEditComponent} from '../weight-edit/weight-edit.component';import {WeightService} from '../weight.service';@@ -8,11 +9,10 @@ import {WeightService} from '../weight.service';templateUrl: './weight-chart.component.html',styleUrls: ['./weight-chart.component.css']})-export class WeightChartComponent implements OnInit {+export class WeightChartComponent implements OnInit, OnDestroy {+ // Chart optionsview: [number, number] = [700, 300];-- // optionslegend: boolean = false;showLabels: boolean = true;animations: boolean = true;@@ -22,14 +22,15 @@ export class WeightChartComponent implements OnInit {showXAxisLabel: boolean = false;timeline: boolean = true;autoScale = true;-colorScheme = {- domain: ['#266dd3', '#E44D25', '#CFC0BB', '#7aa3e5', '#a8385d', '#aae3f5']+ domain: ['#266dd3']};- data : any+ data: any;+ private weightEntries: WeightEntry[] = [];selectedEntry?: WeightEntry;+ private subscription!: Subscription;@ViewChild(WeightEditComponent)edit!: WeightEditComponent;@@ -38,19 +39,30 @@ export class WeightChartComponent implements OnInit {private service: WeightService,) { }- async ngOnInit(): Promise<void> {+ ngOnInit(): void {+ this.subscription = this.service.weightChanged.subscribe(+ (newEntries: WeightEntry[]) => {+ this.weightEntries = newEntries;+ this.processData();+ }+ );+++ }- // TODO: only load service data once- await this.service.loadWeightEntries();- const out = this.service.entries.map(entry => {+ ngOnDestroy(): void {+ this.subscription.unsubscribe();+ }++ private processData() {+ const out = this.weightEntries.map(entry => {return {name: entry.date, value: entry.weight, id: entry.id};});this.data = [{name: $localize`Weight`,series: out}];-}@@ -72,4 +84,5 @@ export class WeightChartComponent implements OnInit {console.log('Deactivate', JSON.parse(JSON.stringify(data)));}+}diff --git a/angular/src/app/weight/weight-edit/weight-edit.component.ts b/angular/src/app/weight/weight-edit/weight-edit.component.tsindex 9e97d46d1..1a613a86e 100644--- a/angular/src/app/weight/weight-edit/weight-edit.component.ts+++ b/angular/src/app/weight/weight-edit/weight-edit.component.ts@@ -11,7 +11,7 @@ import {WeightService} from '../weight.service';export class WeightEditComponent implements OnInit {@Output() closeEdit = new EventEmitter<void>();- @Input() weight?: WeightEntry;+ @Input() weight!: WeightEntry;group!: FormGroup;@@ -25,7 +25,6 @@ export class WeightEditComponent implements OnInit {console.log("this weight is not defined");this.weight = new WeightEntry(new Date(), 0);}-this.initForm();}@@ -46,13 +45,9 @@ export class WeightEditComponent implements OnInit {return;}- this.weight!.weight = this.group.value.weight;- this.weight!.date = this.group.value.date;--if(this.weight?.id) {console.log('editing weight entry ' + this.weight.id);- this.service.updateWeightEntry(this.weight);+ this.service.updateWeightEntry(this.group.value, this.weight.id);} else {console.log('adding new weight entry');this.service.addWeightEntry(this.group.value);diff --git a/angular/src/app/weight/weight-list/weight-list.component.html b/angular/src/app/weight/weight-list/weight-list.component.htmlindex 460dfdc30..7a5110914 100644--- a/angular/src/app/weight/weight-list/weight-list.component.html+++ b/angular/src/app/weight/weight-list/weight-list.component.html@@ -20,11 +20,11 @@[entry]="entry.entry"[dayDiff]="entry.dayDiff"[weightDiff]="entry.weightDiff"- *ngFor="let entry of weightEntries | slice: (page-1) * pageSize : page * pageSize"></app-weight-detail>+ *ngFor="let entry of weightEntriesProcessed | slice: (page-1) * pageSize : page * pageSize"></app-weight-detail></ul><ngb-pagination- [collectionSize]="weightEntries.length"+ [collectionSize]="weightEntriesProcessed.length"[pageSize]="pageSize"[(page)]="page"[boundaryLinks]="true"diff --git a/angular/src/app/weight/weight-list/weight-list.component.ts b/angular/src/app/weight/weight-list/weight-list.component.tsindex b8aff1d01..2e4aa0470 100644--- a/angular/src/app/weight/weight-list/weight-list.component.ts+++ b/angular/src/app/weight/weight-list/weight-list.component.ts@@ -1,5 +1,6 @@-import { Component, OnInit } from '@angular/core';+import {Component, OnDestroy, OnInit} from '@angular/core';import {NgbModal} from '@ng-bootstrap/ng-bootstrap';+import {Subscription} from 'rxjs';import {WeightEntry} from '../models/weight.model';import {WeightService} from '../weight.service';@@ -8,11 +9,13 @@ import {WeightService} from '../weight.service';templateUrl: './weight-list.component.html',styleUrls: ['./weight-list.component.css']})-export class WeightListComponent implements OnInit {- weightEntries: { entry: WeightEntry, weightDiff: number, dayDiff: number }[] = [];+export class WeightListComponent implements OnInit, OnDestroy {+ weightEntriesProcessed: { entry: WeightEntry, weightDiff: number, dayDiff: number }[] = [];+ private weightEntries: WeightEntry[] = [];+ private subscription!: Subscription;/**- Starting page for the pagination+ Starting page for the pagination*/page = 1;@@ -29,33 +32,43 @@ export class WeightListComponent implements OnInit {constructor(private service: WeightService,private modalService: NgbModal- ) { }+ ) {+ }ngOnInit(): void {- this.processWeightEntries();+ this.service.loadWeightEntries();+ this.subscription = this.service.weightChanged.subscribe(+ (newEntries: WeightEntry[]) => {+ this.weightEntries = newEntries;+ this.processWeightEntries();+ }+ );+ }++ ngOnDestroy(): void {+ this.subscription.unsubscribe();}/**- * Processes the weight entries and calculates the difference in days beween+ * Processes the weight entries and calculates the difference in days between* entries.** This could potentially be moved to the model*/- async processWeightEntries(): Promise<void> {- const entries = await this.service.loadWeightEntries();- const nrOfEntries = entries.length;-- entries.forEach((currentEntry, index) => {+ processWeightEntries(): void {+ this.weightEntriesProcessed = [];+ const nrOfEntries = this.weightEntries.length;+ this.weightEntries.forEach((currentEntry, index) => {// Newest entries are the firstconst prevIndex = index + 1;- const weightDiff = prevIndex < nrOfEntries ? currentEntry.weight - entries[prevIndex].weight : 0;- const dayDiff = prevIndex < nrOfEntries ? (currentEntry.date.getTime() - entries[prevIndex].date.getTime()) / (1000 * 3600 * 24) : 0;+ // Calculate the difference to the entry before+ const weightDiff = prevIndex < nrOfEntries ? currentEntry.weight - this.weightEntries[prevIndex].weight : 0;+ const dayDiff = prevIndex < nrOfEntries ? (currentEntry.date.getTime() - this.weightEntries[prevIndex].date.getTime()) / (1000 * 3600 * 24) : 0;- this.weightEntries.push({entry: currentEntry, weightDiff: weightDiff, dayDiff: dayDiff});+ this.weightEntriesProcessed.push({entry: currentEntry, weightDiff: weightDiff, dayDiff: dayDiff});});-}openModal(content: any) {diff --git a/angular/src/app/weight/weight.service.ts b/angular/src/app/weight/weight.service.tsindex 90697e0dc..0c53a6f23 100644--- a/angular/src/app/weight/weight.service.ts+++ b/angular/src/app/weight/weight.service.ts@@ -1,5 +1,6 @@import {HttpClient} from '@angular/common/http';import {Injectable} from '@angular/core';+import {Subject} from 'rxjs';import {environment} from '../../environments/environment';import {AuthService} from '../core/auth.service';import {WeightAdapter, WeightEntry} from './models/weight.model';@@ -10,8 +11,9 @@ import {WeightAdapter, WeightEntry} from './models/weight.model';})export class WeightService {weightEntryUrl = environment.apiUrl + 'weightentry/';+ weightChanged = new Subject<WeightEntry[]>();- entries: WeightEntry[] = [];+ private entries: WeightEntry[] = [];constructor(private http: HttpClient,private weightAdapter: WeightAdapter,@@ -20,6 +22,10 @@ export class WeightService {}+ get weightEntries() {+ return this.entries.slice();+ }+/*** Sorts weight entries by date.@@ -32,29 +38,38 @@ export class WeightService {}- async loadWeightEntries(): Promise<WeightEntry[]> {+ loadWeightEntries(): WeightEntry[] {- const data = await this.http.get<any>(this.weightEntryUrl,- {params: {limit: 500}, headers: this.authService.headers}).toPromise();+ const data = this.http.get<any>(this.weightEntryUrl,+ {params: {limit: 500}, headers: this.authService.headers}).subscribe(data => {+ for (const weightData of data.results) {+ this.entries.push(this.weightAdapter.fromJson(weightData));+ }+ this.sortEntries();+ this.weightChanged.next(this.weightEntries);+ });- for (const weightData of data.results) {- this.entries.push(this.weightAdapter.fromJson(weightData));- }- this.sortEntries();- return this.entries;+ return this.weightEntries;}/*** Updates an existing weight entry*- * @param weight a [WeightEntry] instance+ * @param weightData: weight entry data object+ * @param id: id of the weight entry data to update*/- updateWeightEntry(weight: WeightEntry) {- this.http.patch<any>(this.weightEntryUrl + weight.id + '/',- this.weightAdapter.toJson(weight), {- headers: this.authService.headers- }).subscribe(value => {+ updateWeightEntry(weightData: any, id: number) {++ this.http.patch<any>(this.weightEntryUrl + id + '/',+ weightData, {+ headers: this.authService.headers+ }).subscribe(value => {++ const index = this.findIndexById(id);+ this.entries[index] = this.weightAdapter.fromJson(value);+ this.sortEntries();+ this.weightChanged.next(this.weightEntries);});}@@ -69,6 +84,7 @@ export class WeightService {}).subscribe(value => {this.entries.push(this.weightAdapter.fromJson(value));this.sortEntries();+ this.weightChanged.next(this.weightEntries);});}@@ -78,15 +94,16 @@ export class WeightService {* @param id: ID of the weight entry*/deleteWeightEntry(id: number) {-this.http.delete<any>(this.weightEntryUrl + id + '/', {headers: this.authService.headers- }).subscribe();+ }).subscribe(value => {+ this.entries.forEach((value: WeightEntry, index: number) => {+ if (value.id == id) {+ this.entries.splice(index, 1);+ }+ });- this.entries.forEach((value: WeightEntry, index: number) => {- if (value.id == id) {- this.entries.splice(index, 1);- }+ this.weightChanged.next(this.weightEntries);});}@@ -99,5 +116,13 @@ export class WeightService {return this.entries.find(value => value.id == id);}+ /**+ * Finds the index of a weight entry by its ID+ *+ * @param id: ID of the weight entry+ */+ findIndexById(id: number) {+ return this.entries.findIndex(value => value.id == id);+ }}