2

I'm working on a relatively simple task app and I can't figure out what the best way to set the ID (and any potential other server-created content) in a Task object once the response from the POST request is returned. For example;

// POST Data
{
  title: 'The title for the task',
  due: '2016-01-01'
}

// Response
{
  id: 123,
  title: 'The title for the task',
  due: '2016-01-01'
}

Currently I have the pushing of the new task into the collection occurring in the subscribe function, but that means that the Task is not added to the list (and therefore the page) instantly. What is the best way to allow for the task object to be pushed instantly into the collection, then on response from the API update or replace that object?

I considered editing the last task in the collection but obviously a second task could be added before the response from the first is returned.

The following code shows the current implementation, with the list component and the child form component that emits on event on response.

// task-form.component.ts
addTask(task) {
  this.taskService.create(task)
    .subscribe(savedTask => {
      this.taskAdd.emit(savedTask);
      this.task.title = null;
    });
}

// task-list.component.ts (listening to the taskAdd event)
addTaskToPeriod(task: Task) {
  this.tasks.push(task);
}

Thanks!

James Crinkley
  • 1,398
  • 1
  • 13
  • 33
  • You could also think about client generated IDs using [GUIDs](https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript) ... – david Nov 28 '16 at 17:17

1 Answers1

0

No idea if this is the best way to do this, but since the task object is passed by reference into the addTask method, I just emit the event immediately so that the task appears in the UI, then I set the ID on the task object on response from the API;

addTask(task) {
    // Emit immediately
    this.taskAdd.emit(task);

    this.taskService.create(task)
      .subscribe(savedTask => {
        // Update the task that is now visible in the UI by reference
        task.id = savedTask.id;
      });

    // Full reassignment to prevent further by-reference side effects 
    this.task = {};
  }
James Crinkley
  • 1,398
  • 1
  • 13
  • 33