2017-03-16 29 views
0

我正在嘗試使用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

有誰知道如何解決呢?

回答

2

這裏可能會出現一些問題。

錯誤可能是由於您調用addTodo函數而沒有參數或參數爲undefined的事實造成的。這就是導致你所描述的錯誤的原因。

另一個可能的問題可能是您沒有實現接口的類。雖然這不是嚴格必要的,但它可以幫助您更好地利用TypeScript的類型安全性,從而幫助您防止錯誤。

更新:在您的代碼更新中,確實調用addTodo而沒有參數,這會導致它在函數中未定義。

有幾種方法可以解決這個問題,但我會告訴你一個。在您的組件中,您可以添加屬性id,title,message(請注意,將它們放置在對象中或重命名以保持清晰可能會更好;這只是一個簡單示例)。然後你可以使用這些屬性來添加你的待辦事項。因此,您可以不使用item.id,item.titleitem.message而使用this.id,this.titlethis.message。這些匹配的字段與您提供的HTML模板中的ngModel綁定相關。

+0

謝謝!它的工作原理,這樣做我不需要接口 –

+0

真的,這樣你就不需要接口。儘管使用接口/對象來存儲數據,而不是直接將字段放入組件中,但它可能會更乾淨些。然而,當然這兩種方式都有效。 –

+1

謝謝!現在我會嘗試使用界面來做,只是爲了學習 –