我尝试用Angular 9显示“ Magazines”表,所以我将magazine.component(在Angular中)与后端(在spring-boot中)与HttpClient连接起来。问题是表格显示为空数据。
谢谢您的帮助。
这是Magazine.component.ts:
import { Component, OnInit, Input, ViewChild, Output, EventEmitter } from '@angular/core';
import {MagazineService} from '../magazine.service';
import { MatTableDataSource } from '@angular/material/table';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import { MatFormFieldControl } from '@angular/material/form-field';
@Component({
selector: 'app-magazine',
templateUrl: './magazine.component.html',
styleUrls: ['./magazine.component.css'],
providers: [
{ provide: MatFormFieldControl, useExisting: MagazineComponent }
]
})
export class MagazineComponent implements OnInit {
@Input() label : string;
@Output() action = new EventEmitter<number>();
displayedColumns : string[] = ['Id', 'name', 'author',
'category','numberOfPages','price','nextReleaseDate'];
dataSource : any;
magazinecoll : any;
libraryName : string;
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(private magazineService : MagazineService) { }
ngOnInit(): void {
this.chargerMagazines(this.libraryName);
}
chargerMagazines(libraryName) {
this.libraryName=libraryName;
let magazinecoll = this.magazineService.getMagazineByLibrary(this.libraryName);
magazinecoll.subscribe((data)=> this.dataSource=new MatTableDataSource(this.magazinecoll));
}
}
这是magazine.component.html:
<div fxLayout="row">
<mat-form-field>
<input matInput placeholder="Library name" [(ngModel)]="libraryName" />
</mat-form-field>
<button mat-raised-button color="primary" (click)="chargerMagazines(libraryName)">Get</button>
</div>
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
<ng-container *ngFor="let key of displayedColumns" [matColumnDef]="key">
<th mat-header-cell *matHeaderCellDef mat-sort-header>{{ key }}</th>
<td mat-cell *matCellDef="let element">{{ element[key] }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
<mat-paginator [pageSizeOptions]="[10, 20, 50]" showFirstLastButtons>
</mat-paginator>
这是magazine.service.ts:
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs';
import { Magazine } from './magazine';
@Injectable({
providedIn: 'root'
})
export class MagazineService {
constructor(private http : HttpClient) {}
public getMagazineByLibrary (libraryName : string): Observable<Magazine[]>{
return this.http.get<Magazine[]>("http://localhost:8085/magazines/"+libraryName)
}
}
这是我运行它的结果: