我正在尝试使用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
有谁知道如何解决呢?
谢谢!它的工作原理,这样做我不需要接口 –
真的,这样你就不需要接口。尽管使用接口/对象来存储数据,而不是直接将字段放入组件中,但它可能会更干净些。然而,当然这两种方式都有效。 –
谢谢!现在我会尝试使用界面来做,只是为了学习 –