我正在尝试根据属性值显示数组中的单个对象。
我的交易项目列表有一个 accountId 属性,但我想改为显示帐户名称。所有帐户都加载到accounts$ 数组中。我就是不知道如何正确使用我的 getAccountById 函数
这是组件类
export class NewtransactionComponent implements OnInit {
transaction$: Transaction;
tempItem$: TransactionItem;
accounts$: Array<Account>;
constructor(private data: DataService) { }
ngOnInit() {
this.transaction$ = new Transaction();
this.data.getAccounts().subscribe(data => this.accounts$ = Object.assign(new Array<Account>(), data));
this.tempItem$ = new TransactionItem();
this.transaction$.TransactionDate = new Date();
}
addItem(){
this.transaction$.TransactionItems.push(this.tempItem$);
this.tempItem$ = new TransactionItem();
}
getAccountById(id):Account{
return this.accounts$.find(x => x.id === id);
};
Run Code Online (Sandbox Code Playgroud)
这是给出错误“无法读取未定义的属性'名称'”的html视图
export class NewtransactionComponent implements OnInit {
transaction$: Transaction;
tempItem$: TransactionItem;
accounts$: Array<Account>;
constructor(private data: DataService) { }
ngOnInit() {
this.transaction$ = new Transaction();
this.data.getAccounts().subscribe(data => this.accounts$ = Object.assign(new Array<Account>(), data));
this.tempItem$ = new TransactionItem();
this.transaction$.TransactionDate = new Date();
}
addItem(){
this.transaction$.TransactionItems.push(this.tempItem$);
this.tempItem$ = new TransactionItem();
}
getAccountById(id):Account{
return this.accounts$.find(x => x.id === id);
};
Run Code Online (Sandbox Code Playgroud)
这些是供参考的帐户和交易项目数据模型
export class Account {
Id: string;
Name: string;
Category: string;
SubCategory: string;
}
export class TransactionItem{
Id: number;
TransactionId:number;
Accountid: string;
Amount: number;
CreditDebit: string;
}
Run Code Online (Sandbox Code Playgroud)
我假设错误在这里:{{account.name}}?
这很可能是时间问题。该页面将尝试在从订阅中检索数据之前显示。
解决问题的一种方法是使用 *ngIf
<div class="items-container" *ngIf="account">
Run Code Online (Sandbox Code Playgroud)
这样,在检索到数据之前页面不会尝试显示。
另一种选择是使用安全导航操作符:
{{account?.name}}
Run Code Online (Sandbox Code Playgroud)
问号告诉 Angular 如果帐户为 null 或未定义,则不要尝试读取 name 属性。
编辑:
如果这里有错误:{{getAccountById(item.AccountId).name}},那么它告诉您getAccountById(item.AccountId)未定义或为空。您的其中一笔交易是否可能没有帐户?
更仔细地查看您的代码,JavaScript/TypeScript 区分大小写。因此,如果您使用以下方法声明 id:
Id: string;
Run Code Online (Sandbox Code Playgroud)
(大写 I)
然后您无法使用以下方法访问它:
return this.accounts$.find(x => x.id === id);
Run Code Online (Sandbox Code Playgroud)
(小写)
| 归档时间: |
|
| 查看次数: |
5005 次 |
| 最近记录: |