如何对接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.
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
corspackage: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
To use Angular Material tables, you need to install and import the required modules:
- Install Angular Material and dependencies:
Follow the prompts to choose a theme, typography, and animations.ng add @angular/material - Update your
AppModuleto 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 { }
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); }); } }
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>
- Start your Node.js API:
node your-server-file.js - Start your Angular development server:
ng serve - Open your browser and go to
http://localhost:4200—you should see the table populated with your device data!
- 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
Deviceinterface helps catch errors early and makes your code more maintainable. - Error Handling: The
subscribemethod includes an error handler to debug any issues with fetching data.
内容的提问来源于stack exchange,提问作者Amrita Chandrashekhar

