我正试图把数据传送到有Angular 的前端.试图从另一个api获取数据,但仍然不适用于我.因此,API正在工作,但数据无法显示在前端.我读了文档,但这无助于解决问题.希望有人能帮助我.
Employee Class:
export class Employee {
id!: number;
firstName!: string;
lastName!: string;
emailId!: string;
}
Employee-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Employee } from '../employee';
import { EmployeeService } from '../employee.service';
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
employees!: Employee[];
constructor(private employeeService: EmployeeService) { }
ngOnInit(): void {
this.getEmployees();
}
private getEmployees(){
this.employeeService.getEmployeesList().subscribe(data =>{
this.employees = data;
});
}
}
Employee-list.component.html
<h2> Mitarbeiter Liste</h2>
<table class = "table table-striped">
<thead>
<tr>
<th> Vorname</th>
<th> Nachname</th>
<th> Email</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of employees">
<td>{{ employee.firstName }}</td>
<td>{{ employee.lastName }}</td>
<td>{{ employee.emailId }}</td>
</tr>
</tbody>
</table>
Employee.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Employee } from './employee';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
private baseUrl = 'http://localhost:8080/api/v1/employees';
constructor(private httpClient: HttpClient) { }
getEmployeesList(): Observable<Employee[]>{
return this.httpClient.get<Employee[]>(this.baseUrl);
}
}
App.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EmployeeListComponent } from './employee-list/employee-list.component';
@NgModule({
declarations: [
AppComponent,
EmployeeListComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The API data:
[{"id":1,"firstName":"Frank","lastName":"wettew","emailId":"test@gmail.de"},{id:2,"firstName":"Herbert","lastName":"Hubert","emailId":"herb@gmail.de"}]