我正在嘗試使用Angular 2中的接口。 我已經創建了一個接口和一個組件。Angular 2 Interface
接口:
export interface Items {
id: number;
title: string;
message: string;
done: boolean;
}
組件:
export class AddComponent implements OnInit {
currentItem: string;
todos: any;
constructor(private router: Router) {
this.currentItem = (localStorage.getItem('currentItem')!==null) ? JSON.parse(localStorage.getItem('currentItem')) : [ ];
this.todos = this.currentItem;
}
addTodo(item: Items) {
this.todos.push({
id: item.id,
title: item.title,
message: item.message,
done: false
});
item.title = '';
item.message = '';
localStorage.setItem('currentItem', JSON.stringify(this.todos));
console.log('retorno: ' + this.todos.title + ' titulo: ' + item.title);
this.router.navigate(['./list']);
}
ngOnInit() {}
}
HTML:
<div class="container">
<form (submit)="addTodo()">
<div class="form-group">
<label>Id:</label>
<input [(ngModel)]="id" class="textfield form-control" name="id">
</div>
<div class="form-group">
<label>Titulo:</label>
<input [(ngModel)]="title" class="textfield form-control" name="title">
</div>
<div class="form-group">
<label>Mensagem:</label>
<input [(ngModel)]="message" class="textfield form-control" name="message">
</div>
<button type="submit" class="btn btn-success">Salvar</button>
</form>
</div>
我有一個錯誤:EXCEPTION: Cannot read property 'id' of undefined
有誰知道如何解決呢?
謝謝!它的工作原理,這樣做我不需要接口 –
真的,這樣你就不需要接口。儘管使用接口/對象來存儲數據,而不是直接將字段放入組件中,但它可能會更乾淨些。然而,當然這兩種方式都有效。 –
謝謝!現在我會嘗試使用界面來做,只是爲了學習 –