无法阅读属性' sourceAccount'未定义 - 绑定选择时出现异常

时间:2018-02-04 21:00:25

标签: angular

我收到此错误:

NewTransactionComponent.html:4 ERROR TypeError: Cannot read property 'sourceAccount' of undefined
    at Object.eval [as updateDirectives] (NewTransactionComponent.html:4)

当我尝试在我的html中绑定select时。基本上,在同一页面中将有两个选项填充相同的数据(帐户)。我想传递给每个选择选择哪个帐户的服务,但我收到上面的错误。

新transaction.component.html

<div>
  <div>
  <label>Source Account</label>
  <select [(ngModel)]="transaction.sourceAccount.id">
      <option *ngFor="let a of accounts" [value]="a.id" >{{a.name}}</option>
  </select>
</div>
<div>
  <label>Source Account</label>
  <select  [(ngModel)]="transaction.targetAccount.id" >
      <option *ngFor="let a of accounts" [value]="a.id">{{a.name}}</option>
  </select>
</div>
<div>
  <input type="text" [(ngModel)]="transaction.amount">
</div>
<div>
    <button (click)="addTransaction()">Add</button>
 </div>
</div>

新transaction.component.ts

export class NewTransactionComponent implements OnInit {

  accounts: Account[];
  transaction: Transaction;
  constructor(private accountService: AccountService, private transactionService: TransactionService) { }

  addTransaction(): void {

    //this.transaction.amount= *** here I want fill the variable transaction so I can post it to rest service
    this.transactionService.addTransaction(this.transaction);

  } 

...

我的模特:

transaction.ts

import { Account } from "./account";

export class Transaction {
    idtransaction: number;
    amount: number;
    sourceAccount: Account;
    targetAccount: Account;

    constructor(values: Object = {}) {
      Object.assign(this, values);
    }
}

account.ts

import { User } from "./user";

export class Account {
    id: number;
    name: string = '';
    user: User[] = [];

    constructor(values: Object = {}) {
      Object.assign(this, values);
    }
}

****编辑

export class NewTransactionComponent implements OnInit {

  accounts: Account[];
  transaction: Transaction = new Transaction;
  constructor(private accountService: AccountService, private transactionService: TransactionService) { }

  ngOnInit(): void {
    this.accountService
    .getAllAccounts()
    .subscribe(
      (accounts) => {
        this.accounts = accounts;
      }
    );
  }

  addTransaction(): void {
    this.transactionService.addTransaction(this.transaction);
    //this.router.navigate(['/home']);
  } 
}

1 个答案:

答案 0 :(得分:1)

在设置[(ngModel)]之前,您至少需要一个空的事务对象。否则交易将是未定义的。