You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对接JSON数据并在Angular Material表格中展示设备列表

Hey there! Let's walk through getting your device data from your Node.js API into an Angular Material table step by step. First, I notice there's a mix-up between AngularJS (the older framework) and Angular (2+) in your code—your module.ts is for Angular, but the controller you wrote uses AngularJS syntax. Let's fix that and build out the rest properly.

Step 1: Fix CORS Issue (Critical!)

Your Node API runs on port 3000, and Angular will run on port 4200 by default. Browsers block cross-origin requests by default, so we need to add CORS support to your Node server:

  • Install the cors package:
    npm install cors
    
  • Update your Node.js code to use it:
    const express = require('express'); 
    const bodyParser = require('body-parser'); 
    const cors = require('cors'); // Add this line
    const app = express(); 
    const mysql = require('mysql'); 
    
    app.use(cors()); // Add this line before other middleware
    //parse application/json 
    app.use(bodyParser.json()); 
    
    // ... rest of your Node code stays the same
    
Step 2: Set Up Angular Material

To use Angular Material tables, you need to install and import the required modules:

  • Install Angular Material and dependencies:
    ng add @angular/material
    
    Follow the prompts to choose a theme, typography, and animations.
  • Update your AppModule to import Material table-related modules:
    import { BrowserModule } from '@angular/platform-browser'; 
    import { NgModule } from '@angular/core'; 
    import { HttpClientModule } from '@angular/common/http';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; // Required for Material
    import { MatTableModule } from '@angular/material/table'; // For the table component
    import { MatToolbarModule } from '@angular/material/toolbar'; // Optional: For a header
    
    import { AppComponent } from './app.component'; 
    
    @NgModule({ 
      declarations: [ 
        AppComponent, 
      ], 
      imports: [ 
        BrowserModule, 
        HttpClientModule,
        BrowserAnimationsModule,
        MatTableModule,
        MatToolbarModule
      ], 
      providers: [], 
      bootstrap: [AppComponent] 
    }) 
    export class AppModule { } 
    
Step 3: Rewrite Your Angular Component (Replace AngularJS Controller)

Angular uses components instead of AngularJS-style controllers. Let's update app.component.ts to fetch data and hold the table data:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// Define an interface for your device data to get type safety
export interface Device {
  serialnum: string;
  time: string;
  type: string;
  temparature: string;
  date: string;
  status: string;
  comments: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  displayedColumns: string[] = ['serialnum', 'time', 'type', 'temparature', 'date', 'status', 'comments']; // Columns to show
  devices: Device[] = [];

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.getDevices(); // Fetch data when component loads
  }

  getDevices(): void {
    this.http.get<{status: number, error: null, response: Device[]}>('http://localhost:3000/api/devices')
      .subscribe(response => {
        this.devices = response.response; // Assign the device list from API response
        console.log('Devices loaded:', this.devices);
      }, error => {
        console.error('Error fetching devices:', error);
      });
  }
}
Step 4: Create the Angular Material Table Template

Update app.component.html to render the table:

<mat-toolbar color="primary">
  <span>Device Status Table</span>
</mat-toolbar>

<div class="mat-elevation-z8" style="margin: 20px;">
  <table mat-table [dataSource]="devices">

    <!-- Serial Number Column -->
    <ng-container matColumnDef="serialnum">
      <th mat-header-cell *matHeaderCellDef> Serial Number </th>
      <td mat-cell *matCellDef="let element"> {{element.serialnum}} </td>
    </ng-container>

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

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

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

    <!-- Date Column -->
    <ng-container matColumnDef="date">
      <th mat-header-cell *matHeaderCellDef> Date </th>
      <td mat-cell *matCellDef="let element"> {{element.date | date:'medium'}} </td>
    </ng-container>

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

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

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</div>
Step 5: Run Both Servers
  1. Start your Node.js API:
    node your-server-file.js
    
  2. Start your Angular development server:
    ng serve
    
  3. Open your browser and go to http://localhost:4200—you should see the table populated with your device data!
Key Notes to Remember
  • Angular vs AngularJS: Angular (2+) uses components and TypeScript, while AngularJS is the older framework with controllers and plain JS. Your original controller code was AngularJS, which doesn't work with your Angular module.ts.
  • Type Safety: Using the Device interface helps catch errors early and makes your code more maintainable.
  • Error Handling: The subscribe method includes an error handler to debug any issues with fetching data.

内容的提问来源于stack exchange,提问作者Amrita Chandrashekhar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 20:12:35