RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 876165
Accepted
titaniche
titaniche
Asked:2020-09-01 20:38:53 +0000 UTC2020-09-01 20:38:53 +0000 UTC 2020-09-01 20:38:53 +0000 UTC

Angular CLI 和材料表

  • 772

大家好。请告诉我为什么我不在材料表中显示数据。我完全无法理解。而且,还有数据,而且行数和实际数据量相对应,但表根本就是空的。

空表

设备模型.ts

export class DeviceModel {
  private _id: number;
  private _device: string;
  private _status: string;
  private _lastUpdate: Date;

  contructor(id?: number,
             device?: string,
             status?: string,
             lastUpdate?: Date) {
    this._id = id;
    this._device = device;
    this._status = status;
    this._lastUpdate = lastUpdate;
  }

  get id(): number {
    return this._id;
  }

  set id(value: number) {
    this._id = value;
  }

  get device(): string {
    return this._device;
  }

  set device(value: string) {
    this._device = value;
  }

  get status(): string {
    return this._status;
  }

  set status(value: string) {
    this._status = value;
  }

  get lastUpdate(): Date {
    return this._lastUpdate;
  }

  set lastUpdate(value: Date) {
    this._lastUpdate = value;
  }
}

设备服务.ts

import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable, of} from "rxjs";
import {AppConfig} from "../../../config/app.config";
import {DeviceModel} from "./device.model";
import {LoggerService} from "../../../core/shared/logger.service";
import {catchError, tap} from "rxjs/operators";

@Injectable({
  providedIn: 'root'
})
export class DeviceService {

  private readonly deviceUrl: string;

  constructor(private httpClient: HttpClient) {
    this.deviceUrl = AppConfig.endpoints.device;
  }

  private static handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      LoggerService.log(`${operation} failed: ${error.message}`);

      if (error.status >= 500) {
        throw error;
      }

      return of(result as T);
    };
  }

  public getAllDevices(): Observable<DeviceModel[]> {
    return this.httpClient.get<DeviceModel[]>(this.deviceUrl)
      .pipe(
        tap(() => LoggerService.log(`fetched devices`)),
        catchError(DeviceService.handleError('getDevices', []))
      );
  }
}

设备列表.component.ts

import {Component, OnInit} from '@angular/core';
import {DeviceModel} from "../../shared/device.model";
import {DeviceService} from "../../shared/device.service";

@Component({
  selector: 'app-device',
  templateUrl: './device-list.component.html',
  styleUrls: ['./device-list.component.scss']
})

export class DeviceListComponent implements OnInit {

  devices: DeviceModel[];
  displayedColumns: ['id', 'device', 'state', 'lastUpdate'];

  constructor(private deviceService: DeviceService) {
  }

  ngOnInit() {
    this.deviceService.getAllDevices().subscribe((devices: DeviceModel[]) => {
      this.devices = devices
    });
    console.log(this.devices);
  }

}

设备列表.components.html

  <!-- Table container-->
  <div class="table-container">
    <mat-table #deviceTable [dataSource]="devices">

      <!-- Id Column -->
      <ng-container matColumnDef="id">
        <mat-header-cell *matHeaderCellDef> Id </mat-header-cell>
        <mat-cell *matCellDef="let device">{{device.id}}</mat-cell>
      </ng-container>

      <!-- Device Column -->
      <ng-container matColumnDef="device">
        <mat-header-cell *matHeaderCellDef> Device </mat-header-cell>
        <mat-cell *matCellDef="let device">{{device.device}}</mat-cell>
      </ng-container>

      <!-- Status Column -->
      <ng-container matColumnDef="state">
        <mat-header-cell *matHeaderCellDef> State </mat-header-cell>
        <mat-cell *matCellDef="let device">{{device.state}}</mat-cell>
      </ng-container>

      <!-- Lst update Column -->
      <ng-container matColumnDef="lastUpdate">
        <mat-header-cell *matHeaderCellDef> Last update </mat-header-cell>
        <mat-cell *matCellDef="let device">{{device.lastUpdate}}</mat-cell>
      </ng-container>

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

    </mat-table>
  </div>
  <!-- Table container-->

如果您在常规 html 表中显示 - 数据就在那里。

html表

<div>
    <table>
      <thead>
      <tr>
        <th>Id</th>
        <th>DeviceModel</th>
        <th>State</th>
        <th>Last update</th>
      </tr>
      </thead>

      <tbody>
      <tr *ngFor="let device of devices">
        <td>{{device.id}}</td>
        <td>{{device.device}}</td>
        <td>{{device.status}}</td>
        <td>{{device.lastUpdate}}</td>
      </tr>
      </tbody>
    </table>
  </div>

当然,我倾向于相信 DeviceService 中的 DeviceModel 中的数据映射在某种程度上是错误的。但我不知道出了什么问题。我还在控制台中附加了日志的内容。

铬日志

一般来说,很明显我的设备数组是未定义的。请告诉我如何解决这种情况?

提前非常感谢大家。

PS:最近几天,我一直在学习 Angular,所以如果我有时会忽略相当明显的事情,我深表歉意。

我已经根据答案进行了调整。

谢谢,有帮助,现在可以了。

angular
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    overthesanity
    2020-09-01T23:21:54Z2020-09-01T23:21:54Z

    首先,该data-bound属性dataSource需要一个实例MatTableDataSource,而不是普通数组:

    import { MatTableDataSource } from '@angular/material';
    
    @Component({ ... })
    export class DeviceListComponent {
        public devices = new MatTableDataSource<DeviceModel>([]);
    
        constructor(private deviceService: DeviceService) {
            this.deviceService.getDevices().toPromise().then((devices: DeviceModel[]) => {
                this.devices.data = devices;
            });
        }
    }
    

    其次,不需要创建如此复杂的模型,例如DeviceModel私有属性、getter 和 setter,在这种情况下,一个简单的合约就足够了:

    export interface Device {
        id: number;
        device: string;
        status: string;
        lastUpdate: Date;
    }
    

    另外,你初始化不正确displayedColumns,在这里你只是声明一个类型:

    displayedColumns: ['id', 'device', 'state', 'lastUpdate'];
    

    你需要初始化:

    displayedColumns: ReadonlyArray<string> = ['id', 'device', 'state', 'lastUpdate'];
    

    将lastUpdate类型转换number为Date:

    import { tap, catchError } from 'rxjs/operators';
    
    @Injectable({
        providedIn: 'root'
    })
    export class DeviceService {
        private readonly deviceUrl: string = AppConfig.endpoints.device;
    
        constructor(private http: HttpClient) {}
    
        public getAllDevices(): Promise<DeviceModel[]> {
            return this.http.get<DeviceModel[]>(this.deviceUrl).pipe(
                tap(() => LoggerService.log(`fetched devices`))
            ).toPromise().then((devices: DeviceModel[]) => {
                devices.forEach((device: DeviceModel) => {
                    device.lastUpdate = new Date(device.lastUpdate);
                });
    
                return devices;
            });
        }
    }
    

    在组件中,我们只需在构造函数中调用这个方法:

    constructor(private deviceService: DeviceService) {
        this.deviceService.getAllDevices().then((devices: DeviceModel[]) => {
            this.dataSource.data = devices;
        });
    }
    

    同样在模板中,您现在可以使用DatePipe

    • 0

相关问题

  • 角。上下文菜单

  • 导航到另一个页面Angular 6时记住树状态

  • 将数据从组件传递到服务。角 2

  • 角 6 错误 500

  • 为什么@input 不能以角度工作

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    是否可以在 C++ 中继承类 <---> 结构?

    • 2 个回答
  • Marko Smith

    这种神经网络架构适合文本分类吗?

    • 1 个回答
  • Marko Smith

    为什么分配的工作方式不同?

    • 3 个回答
  • Marko Smith

    控制台中的光标坐标

    • 1 个回答
  • Marko Smith

    如何在 C++ 中删除类的实例?

    • 4 个回答
  • Marko Smith

    点是否属于线段的问题

    • 2 个回答
  • Marko Smith

    json结构错误

    • 1 个回答
  • Marko Smith

    ServiceWorker 中的“获取”事件

    • 1 个回答
  • Marko Smith

    c ++控制台应用程序exe文件[重复]

    • 1 个回答
  • Marko Smith

    按多列从sql表中选择

    • 1 个回答
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Suvitruf - Andrei Apanasik 什么是空? 2020-08-21 01:48:09 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5