The data in my material table is changing when I change the route. for example if I change the route and go back to the table route, the existing data is doubled.
So I want to show some data in my Angular app that has been pulled from my firebase database. Currently the data is in the form of an Observable.
I've made a new class that extends the DataSource class from the RxJS library. this class has a connect method where I return my data as an observable.
import { User } from './../models/user.model';
import { FirestoreService } from './../services/firestore.service';
import { Component, OnInit } from '@angular/core';
import {MatTableDataSource} from '@angular/material';
import { ChangeDetectorRef } from '@angular/core'
import { DataSource } from '@angular/cdk/table';
import { Observable } from 'rxjs';
@Component({
selector: 'app-klantenoverzicht',
templateUrl: './klantenoverzicht.component.html',
styleUrls: ['./klantenoverzicht.component.css']
})
export class KlantenoverzichtComponent implements OnInit {
users: UserDataSource;
displayedCols: string[] = ["uid", "naam", "adres", "telefoonnummer", "isKlant"];
constructor(private db: FirestoreService, private changeDetectorRef: ChangeDetectorRef) { }
ngOnInit() {
// this.db.getUsers()
// .subscribe(users => {
// this.users = new MatTableDataSource(users);
// this.users.data = users;
// this.changeDetectorRef.detectChanges();
// console.log(this.users)
// });
this.users = new UserDataSource(this.db);
// this.changeDetectorRef.detectChanges();
}
}
export class UserDataSource extends DataSource<any>{
constructor(private db: FirestoreService){
super();
}
connect(): Observable<User[]>{
return this.db.getUsers();
}
disconnect(){}
}
Above is the component that generates the table data.
<table mat-table [dataSource]="users">
<ng-container matColumnDef="uid">
<th mat-header-cell *matHeaderCellDef> GebruikersID </th>
<td mat-cell *matCellDef="let element"> {{element.uid}} </td>
</ng-container>
<ng-container matColumnDef="naam">
<th mat-header-cell *matHeaderCellDef> Naam </th>
<td mat-cell *matCellDef="let element"> {{element.naam}} </td>
</ng-container>
<ng-container matColumnDef="adres">
<th mat-header-cell *matHeaderCellDef> Adres </th>
<td mat-cell *matCellDef="let element"> {{element.adres}} </td>
</ng-container>
<ng-container matColumnDef="telefoonnummer">
<th mat-header-cell *matHeaderCellDef> Telefoonnummer </th>
<td mat-cell *matCellDef="let element"> {{element.telefoonnummer}} </td>
</ng-container>
<ng-container matColumnDef="isKlant">
<th mat-header-cell *matHeaderCellDef> Rol </th>
<td mat-cell *matCellDef="let element"> Klant </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedCols"></tr>
<tr mat-row *matRowDef="let row; columns: displayedCols; let entry" [ngClass]="{ 'hide' : entry.isKlant == false}" ></tr>
</table>
The actual result is when change routes back and forth, the rows in the table keep adding up with the same data.