Неизвестная ошибка столбца MatTableDataSource с Firebase - PullRequest
0 голосов
/ 06 августа 2020

Я пытаюсь отобразить данные элемента, используя Angular Таблица матов материалов. Последняя идея, которую мне пришлось сделать для отображения данных, заключалась в том, чтобы добавить к нему * ngIf = "dataSource", чтобы предотвратить его загрузку до прибытия данных, но все равно не повезло. Я не понимаю, почему таблица не отображается, данные записываются в консоль до того, как я создам экземпляр matTableDataSource. Мои columnDefs соответствуют свойствам объекта. Я просто не могу понять, что делаю не так. Ошибка, которую я получаю в консоли: "Не удалось найти столбец с идентификатором" name "."

Я очень признателен всем, кто найдет время, чтобы взглянуть на это, поскольку я потеря относительно того, что попробовать дальше. Я помещу весь соответствующий код ниже:

DataTable HTML

<div>
<mat-table *ngIf="dataSource" [dataSource]="dataSource">
  <ng-container matColumnDef="sku">
    <th mat-header-cell *matHeaderCellDef> Sku </th>
    <td mat-cell *matCellDef="let item"> {{item.sku}} </td>
  </ng-container>

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let item"> {{item.name}} </td>
  </ng-container>

  <ng-container matColumnDef="className">
    <th mat-header-cell *matHeaderCellDef> Class </th>
    <td mat-cell *matCellDef="let item"> {{item.className}} </td>
  </ng-container>

  <ng-container matColumnDef="categoryName">
    <th mat-header-cell *matHeaderCellDef> Category </th>
    <td mat-cell *matCellDef="let item"> {{item.categoryName}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let myRowData; columns: displayedColumns;"></tr>
</mat-table>
</div>

DataTable TS File

import { Component, OnInit, OnDestroy, AfterViewInit } from "@angular/core";
import { FirebaseService } from "./../../../core/services/firebase/firebase.service";
import { MatTableDataSource } from '@angular/material/table';
import { Item } from "../../../models/item.model";

interface Product {
  name: string,
  sku: number,
  className: string,
  categoryName: string
}

@Component({
  selector: "app-itemtable",
  templateUrl: "./itemtable.component.html",
  styleUrls: ["./itemtable.component.css"],
})
export class ItemtableComponent implements OnInit, OnDestroy, AfterViewInit {
  displayedColumns = ["name", "sku", "className", "categoryName"];
  dataSource: MatTableDataSource<Item> = null
  itemList: Item[];

  constructor(private firebaseService: FirebaseService) {

  }

  ngOnInit(): void {
    this.firebaseService.items.subscribe((items: Item[]) => {
      this.dataSource = new MatTableDataSource<Item>(items);
      console.log(items);
    })
  }

  ngOnDestroy(): void {
  }

  ngAfterViewInit(): void {
    console.log('after view init\'d....')
  }
}

Firebase Service:

import { Injectable } from "@angular/core";
import { AngularFirestore } from "@angular/fire/firestore";
import { Observable, BehaviorSubject, Subject } from "rxjs";
import { switchMap } from "rxjs/operators";
import { Category } from "../../../models/category.model";
import { Class } from "../../../models/class.model";
import { Item } from "../../../models/item.model";

@Injectable({
  providedIn: "root",
})
export class FirebaseService {
  items: Observable<Item[]>;
  categories: Observable<Category[]>;
  classes: Observable<Class[]>;
  selectedCategoryID$: BehaviorSubject<number | null>;
  selectableClasses: Observable<Class[]>;
  itemsCollection: any;
  itemsData: Item[];

  constructor(private firestore: AngularFirestore) {
    this.items = this.firestore.collection<Item>("Items").valueChanges();
    this.categories = this.firestore.collection("Categories").valueChanges();
    this.classes = this.firestore.collection("Classes").valueChanges();
    this.itemsCollection = this.firestore.collection("Items");

    this.items.subscribe(items => {
      this.itemsData = items;
      console.log("Service fetch is done: ", items);
    });

    this.selectedCategoryID$ = new BehaviorSubject(null);
    this.selectableClasses = this.selectedCategoryID$.pipe(
      switchMap((categoryID) =>
        firestore
          .collection("Classes", (ref) => ref.where("catID", "==", categoryID))
          .valueChanges()
      )
    );
  }

  /**
   * getInventory
   */
  public getInventory(): any {
    return this.items
  }

  public getCategories(): Observable<Category[]> {
    return this.firestore.collection("Categories").valueChanges();
  }

  public getClasses(): Observable<Class[]> {
    return this.firestore.collection("Classes").valueChanges();
  }

  public getSelectableClasses(): Observable<Class[]> {
    return this.selectableClasses;
  }

  public addItem(item: Item): void {
    this.itemsCollection.add({ ...item });
  }

  public filterClasses(categoryID: number): void {
    console.log("filtering classes!");
    this.selectedCategoryID$.next(categoryID);
    this.selectableClasses.forEach((itemClass) => console.log(itemClass));
  }
}

Модель товара:

export class Item {
  constructor(
    public name: string = 'Example Name',
    public sku: number = 100101,
    public sellingPrice: number = 1.11,
    public buyingCost: number = 1.11,
    public categoryID: number = 1001,
    public categoryName: string = 'Cigarillos', // category ID
    public classID: number = 10001, // class ID
    public className: string = 'Dutch Master',
    public vendors: any[] = [],
    public image: string = '//imagestring', // url
    public description: string = 'Example Description',
    public sellableUnits: "BOX" | "EACH" | "CASE" = "BOX",
    public unit1: { type: "BOX" | "EACH" | "CASE", barCode: string } = { type: "BOX", barCode: "010293019" },
    public unit2: { type: "BOX" | "EACH" | "CASE", barCode: string } = { type: "EACH", barCode: "010293018" },
    public unit3: { type: "BOX" | "EACH" | "CASE", barCode: string } = { type: "CASE", barCode: "010293016" },
  ) { }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...