My Angular2 component is trying to obtain an ID from another service that returns a promise. To ensure that I receive the data before proceeding, I must await the Promise. Here's a snippet of what the component code looks like:
export class AddTodoComponent implements OnInit {
public todo: TodoItem;
constructor(private todoService: TodoService,
private router: Router) {
this.todo = new TodoItem();
}
saveItem(){
this.todoService.getItems().then(t=>{
this.todo.item.id = t.length;
this.todoService.addItem(this.todo);
});
}
}
Unfortunately, when the saveItem function runs, it triggers an error in the console saying:
EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot set property 'id' of undefined
The service simply returns a Promise.resolve(data)
containing the necessary items, and I have confirmed that it does return the expected data. However, now it appears that within the 'thennable' part of the promise, I can no longer access this.todo
, likely because 'this' now points to the promise instead of the class.
What would be the correct or preferred way to resolve this issue?