Как я могу решить эту ошибку и почему она произошла? - PullRequest
0 голосов
/ 18 мая 2019

Реализация AngularMaterial Таблица с заголовками сортировки Я получаю эту ошибку в консоли:

ОШИБКА TypeError: Невозможно установить свойство 'sort' из неопределенного в

, и этоОшибка в терминале:

ошибка TS2740: в типе 'MatTableDataSource' отсутствуют следующие свойства из типа 'Employee []': длина, pop, push, concat и другие значения.

error TS2322: Тип 'MatSort' нельзя назначить типу '(CompareFn ?: (a: Employee, b: Employee) => number) => Employee []'.

Тип 'MatSort' не соответствует дляподпись '(сравнитеFn ?: (a: Employee, b: Employee) => number): Employee []'.

Я не могу получить от меня то, что он хочет.Буду признателен за любые подсказки!

Я использовал код из документации AngularMaterial, за исключением интерфейса для данных.Может ли это быть проблемой?

EmployeeListComponent


import { Component, OnInit, ViewChild } from '@angular/core';
import { MatSort, MatTableDataSource } from '@angular/material';
import { AngularFirestore } from '@angular/fire/firestore';
import { EmployeeService } from '../shared/employee.service';
import { Employee } from '../shared/employee';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.scss']
})
export class EmployeeListComponent implements OnInit {

  displayedColumns: string[] = ['fullname', 'position', 'mobile'];
  dataSource;

  @ViewChild(MatSort) sort: MatSort;

  constructor(private service: EmployeeService) { }

  ngOnInit() {
    this.service.getEmployees().subscribe(employees => {
      this.dataSource = new MatTableDataSource(employees);
      console.log(this.dataSource);
    });
    this.dataSource.sort = this.sort;

  }

}


EmployeeList HTML


<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">

  <!-- Position Column -->
  <ng-container matColumnDef="fullname">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Full Name </th>
    <td mat-cell *matCellDef="let element"> {{element.fullname}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Position </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

  <!-- Weight Column -->
  <ng-container matColumnDef="mobile">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Mobile </th>
    <td mat-cell *matCellDef="let element"> {{element.mobile}} </td>
  </ng-container>

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


EmployeeService


getEmployees() {
    return this.firestore.collection<Employee>('employees')
      .snapshotChanges()
      .pipe(
        map(actions => actions.map(a => {
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;
          return { id, ...data } as Employee;
       })
        )
      );
}

Класс сотрудника


export class Employee {
  id: string;
  fullname: string;
  empCode: string;
  position: string;
  mobile: string;
}


Ответы [ 2 ]

0 голосов
/ 18 мая 2019

Вы пытаетесь получить доступ к данным вне подписки, они должны быть внутри.

После этого у вас возникнут проблемы с тем, что this.sort не определено в хуке ngOnInit, это происходит потому, что вы пытаетесь получить доступ к HTML-элементу, который еще не был нарисован.(MatSort)

Существует ловушка жизненного цикла, которую вы можете использовать, чтобы гарантировать, что представление готово к доступу @ViewChild, это ngAfterViewInit, запускается только при отрисовке HTML.

Попробуйте структурировать так.


import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { MatSort, MatTableDataSource } from '@angular/material';
import { AngularFirestore } from '@angular/fire/firestore';
import { EmployeeService } from '../shared/employee.service';
import { Employee } from '../shared/employee';

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.scss']
})
export class EmployeeListComponent implements AfterViewInit{

  displayedColumns: string[] = ['fullname', 'position', 'mobile'];
  dataSource;

  @ViewChild(MatSort) sort: MatSort;

  constructor(private service: EmployeeService) { }

  ngAfterViewInit(): void
  {
    this.service.getEmployees().subscribe(employees => {
      this.dataSource = new MatTableDataSource(employees);
      if (this.sort) // check it is defined.
      {
          this.dataSource.sort = this.sort;
      }
    });
  }

}

Документация AfterViewInit Lifecycle // Подробнее .

0 голосов
/ 18 мая 2019

В целом ваш код выглядит хорошо, но эта строка

this.dataSource.sort = this.sort;

находится не в том месте, его следует поместить в блок subscribe.

Причина для ERROR TypeError: Cannot set property 'sort' of undefined

Вы передаете свой синхронный код асинхронно, и я имею в виду, что ваш код subscribe будет выполняться только при возврате ответа от API (от 1 до 2 секунд), но this.dataSource.sort = this.sort; не будет ждать ответа, потому что он синхронный код, и он продолжит свое выполнение независимо от запроса HTTP, а ваш объект dataSource будет undefined, поэтому вам нужно переместить его в асинхронную часть.

Ваш код будет выглядеть так:

ngOnInit() {
    this.service.getEmployees().subscribe(employees => {
      this.dataSource = new MatTableDataSource(employees);
      console.log(this.dataSource);
      this.dataSource.sort = this.sort; <- note this line 

   });   
}
...