首页 > 解决方案 > Angular Web应用程序-打字稿http数据问题

问题描述

我正在使用 Angular 和 SpringMVC 框架构建一个 webapp。我正在尝试加载用户列表(在代码中名为“consulenti”)。来自后端的 http 请求一切正常但是当我尝试在前端部分使用 TypeScript 处理数据时,我不断收到如下错误:

无法在 TablesComponent.ngOnInit 设置未定义的属性“headerRow”(webpack-internal:///./src/app/tables/tables.component.ts:27

无法读取未定义的属性“headerRow”

无法读取未定义的属性“推送”

等等与其他属性。

我正在尝试使用免费的角度仪表板客户端作为模板在表格中显示数据。

下面是代码。

表.component.ts

export class TablesComponent implements OnInit {
public consulenti: Consulente[];
public consulentiData: TableData;
private rows: number;
private cols: number;

constructor(private dataService: DataService) {} // Service injection

setRowData() {
    if (this.rows != undefined && this.cols != undefined) {
        for (let i = 0; i < this.cols; i++) this.consulentiData.dataRows[i] = this.consulenti[i].stringify();
    }
    // else error
}

ngOnInit() {
    this.consulentiData.headerRow = ['Id', 'Nome', 'Cognome', 'E-mail', 'Scadenza contratto'];
    this.dataService.getConsulenti().subscribe(data => {
        for (let i = 0; i < data.length; i++) this.consulenti.push(data[i]);
    });
    this.rows = this.consulenti.length;
    this.cols = this.consulenti[0].stringifyFields;
    this.consulentiData.headerRow = ['Id', 'Nome', 'Cognome', 'E-mail', 'Scadenza contratto'];
    this.setRowData();
}

表格模板.html

<div class="content table-responsive table-full-width">
    <table class="table table-hover table-striped">
        <thead>
            <tr>
                <th *ngFor="let cell of consulentiData.headerRow">{{ cell }}</th>
            </tr>
       </thead>
       <tbody>
           <tr *ngFor="let row of consulentiData.dataRows">
               <td *ngFor="let cell of row">{{cell}}</td>
           </tr>
        </tbody>
    </table>
</div>

非常感谢您!

更新

当从 http 请求中检索数据到数组“consulenti”时,它现在卡在订阅中。从调试器观察复制操作进展顺利,但订阅结束后数组再次变为空。

代码

this.dataService.getConsulenti().subscribe((data: Consulente[]) => {
        this.consulenti = data;
}); // stuck after this.

标签: angulartypescript

解决方案


如下定义它们:

public consulenti: any[] = [];
public consulentiData:any = {};   

编辑

访问订阅数据:

ngOnInit() {
    this.consulentiData.headerRow = ['Id', 'Nome', 'Cognome', 'E-mail', 'Scadenza contratto'];
    this.dataService.getConsulenti().subscribe(data => {
    this.consulenti = data;
    this.rows = this.consulenti.length;
    this.cols = this.consulenti[0].stringifyFields;
    this.consulentiData.headerRow = ['Id', 'Nome', 'Cognome', 'E-mail', 'Scadenza contratto'];
    this.setRowData();
    });
}

推荐阅读