因此,我遵循了https://angular.io/tutorial/toh-pt6中的教程。我已经根据我的具体案例定制了本教程,它只是显示了一个仪表板。当我使用本地模拟时,我的代码运行良好。当我升级到内存中的 web api 时,事情就出错了。
我已经检查了实时代码示例(参考https://stackblitz.com/angular/vvxldjlmnna)并且无法真正找到我做错的影响代码。
首先,我使用npm install angular-in-memory-web-api --save
. 正如 CLI 所提到的,我检查了 node_modules 并看到它确实已成功下载。检查package.json文件,我可以看到在依赖项“angular-in-memory-web-api”:“^0.6.1”中已添加
在app.module.ts 中,我按以下特定顺序导入了这些模块:
@NgModule({
FormsModule,
HttpClientModule,
HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService),
// I also tried:
// HttpClientInMemoryWebApiModule.forRoot(
// InMemoryDataService, { dataEncapsulation: false }
// ),
AppRoutingModule
我正在使用路由器插座来显示仪表板。为此,我使用了一个路由器模块:
const routes: Routes = [{ path: 'dashboard', component: DashboardComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
在我的 in-memory-data.service.ts文件中
export class InMemoryDataService implements InMemoryDbService {
createDb() {
const DashboardReports = [
{ id: 1, date: new Date(2018, 8, 3, 0, 0, 0, 0), overtime: 0, project: 'W31226', superintendent: 'Toon', km: 105, status: 1 },
{ id: 2, date: new Date(2018, 8, 4, 0, 0, 0, 0), overtime: 1.75, project: 'W31226', superintendent: 'Toon', km: 105, status: 2 }
];
return {DashboardReports}; // I paid specific attention to the curly braces here
}
}
// Overrides the genId method to ensure that a hero always has an id.
// If the DashboardReports array is empty,
// the method below returns the initial number (21).
// if the DashboardReports array is not empty, the method below returns the highest
// report id + 1.
genId(dashboardreport: DashboardReport[]): number {
return dashboardreport.length > 0 ? Math.max(...dashboardreport.map(report => report.id)) + 1 : 21;
}
在我的dashboard.service.ts文件中,我注入HttpClient 并从api 调用dashboarddata,从'rxjs' 导入Observable 和从'@angular/common/http' 导入HttpClient。这是仪表板服务:
private dashboardDataUrl = 'api/dashboard';
constructor(private http: HttpClient) { }
/** GET Dashboard Reports from the server */
getDashboardReports (): Observable<DashboardReport[]> {
return this.http.get<DashboardReport[]>(this.dashboardDataUrl);
}
然后在仪表板组件中,我为数据调用服务:
ngOnInit() {
this.getReports();
}
getReports(): void {
this.dashboardService.getDashboardReports().subscribe(reports => this.dashboardReports = reports);
}
对于 DashboardReport 类,我有:
export class DashboardReport{
id: number;
date: Date;
overtime: number;
project: string;
superintendent: string;
km: number;
status: number;
}