Данные в моей таблице материалов меняются, когда я меняю маршрут. например, если я изменю маршрут и вернусь к таблице маршрутов, существующие данные будут удвоены.
Итак, я хочу показать некоторые данные в моем приложении Angular, которые были извлечены из моей базы данных Firebase. В настоящее время данные представлены в форме наблюдаемой.
Я создал новый класс, который расширяет класс DataSource из библиотеки RxJS. у этого класса есть метод подключения, в котором я возвращаю свои данные как наблюдаемые.
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(){}
}
Выше находится компонент, который генерирует данные таблицы.
<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>
Фактический результат заключается в том, что при изменении маршрутов назад и вперед строки в таблице продолжают складываться с одинаковыми данными.