这个问题我已经纠结了一段时间了。我只是想加载一个包含Id、Name和Create Date列的表到页面中。我的API方法在Visual Studio中的控制器类中运行良好。我以前在控制台中遇到过此错误:
TypeError:无法读取未定义的属性“id”。
此错误也出现在
name
如果我删除
id
等等
我做了一些研究,了解到我可以使用
?
elvis操作符,我已经在HTML中实现了它。实现elvis运算符后,错误消失了,但所有表值现在显示为
NaN
. 在Network in Developer Tools下,我可以单击我的表名并查看数据填充到我的表中。
知道问题是什么吗?我已包含以下代码:
测试表tburns列表。组成部分html
<div>
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Create Date</th>
</tr>
<tr *ngFor="let test-table-tburns of testTableTburnsList">
<td>{{ test-table-tburns?.id }}</td>
<td>{{ test-table-tburns?.name }}</td>
<td>{{ test-table-tburns?.createDate }}</td>
</tr>
</table>
</div>
测试表tburns列表。组成部分规范ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TestTableTburnsListComponent } from './test-table-tburns-list.component';
describe('TestTableTburnsListComponent', () => {
let component: TestTableTburnsListComponent;
let fixture: ComponentFixture<TestTableTburnsListComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ TestTableTburnsListComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestTableTburnsListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
测试表tburns列表。组成部分ts
import { Component, OnInit } from '@angular/core';
import { TestTableTburnsApiService } from '../../../services/test-table-tburns-api.service';
import { TestTableTburnsModel } from '../../../models/test-table-tburns-model';
@Component({
selector: 'app-test-table-tburns-list',
templateUrl: './test-table-tburns-list.component.html',
styleUrls: ['./test-table-tburns-list.component.css']
})
export class TestTableTburnsListComponent implements OnInit {
testTableTburnsList: Array<TestTableTburnsModel>;
title = "Hello TestTableTburns List";
constructor(private testTableTburnsApi: TestTableTburnsApiService) { }
ngOnInit() {
this.testTableTburnsApi
.getTestTableTburns()
.subscribe(_ => this.testTableTburnsList = _, e => console.log(e));
}
}
测试表tburns api。服务规范ts
import { TestBed, inject } from '@angular/core/testing';
import { TestTableTburnsApiService } from './test-table-tburns-api.service';
describe('TestTableTburnsApiService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [TestTableTburnsApiService]
});
});
it('should be created', inject([TestTableTburnsApiService], (service: TestTableTburnsApiService) => {
expect(service).toBeTruthy();
}));
});
测试表tburns api。服务ts
import { Injectable } from '@angular/core'
import { Http, Response, Headers } from '@angular/http';
import { environment } from '../../environments/environment';
import 'rxjs/add/operator/map';
@Injectable()
export class TestTableTburnsApiService {
domain : string;
constructor(public http: Http){
this.domain = environment.apiUrl;
}
public getTestTableTburns(){
let uri = this.domain + `/api/test-table-tburns`;
return this.http
.get(uri)
.map((res: Response) => {
return res.json();
})
;
}
}