1

I have an Angular 2 app with an events service which has a delete method:

let EVENTS: TimelineEvent[] = [
    {
      event: 'foo',
      timestamp: 1512205360,
    },
    {
      event: 'bar',
      timestamp: 1511208360,
    }
  ];

@Injectable()
export class EventsService {

  getEvents(): Promise<TimelineEvent[]> {
    return Promise.resolve(EVENTS);
  }

  deleteEvent(deletedEvent) {
    EVENTS = EVENTS.filter((event) => event.timestamp != deletedEvent.timestamp);
  }
}

My main component displays these events, and uses an onClick handler to call the service's deleteEvent method:

@Component({
  selector: 'my-app',
  providers: [EventsService],
  template: `
    <div>
      <event *ngFor="let timelineEvent of events" [timelineEvent]="timelineEvent" [deleteEvent]="deleteEvent"></event>
    </div>
  `,
})
export class App implements OnInit {
  constructor(private eventsService: EventsService) {

  }
  events

  getEvents(): void {
    this.eventsService.getEvents().then(events => this.events = events);
  }

  deleteEvent(event): void {
    this.eventsService.deleteEvent(event); 
  }

  ngOnInit(): void {
    this.getEvents();
  }
}

I can see by console.logging the EVENTS array that this is correctly updated. But the display is not updated. Where am I going wrong?

Example code here: https://plnkr.co/edit/cENnHeHORnDT50RaTyoI.

1 Answer 1

1

You remove the event in your service, not in your component. The list of event in your component remains unupdated.

A way to solve it:

1 - Make the deleteEvent method of your service returning promise:

deleteEvent(deletedEvent) {
    EVENTS = EVENTS.filter((event) => event.timestamp !== deletedEvent.timestamp);
    return Promise.resolve("Successfully deleted");
}

2 - And in your component, reload events on the success of the deleting action:

deleteEvent = (event) => {
    this.eventsService.deleteEvent(event).then(res => this.getEvents()); 
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I've added this.getEvents() to my component's delete method but now it returns the error this.getEvents is not a function. I've updated the Plunker code.
Updated Plunker - I still get TypeError: _this.getEvents is not a function.
Working! Why does the arrow function format work? Just curious.
By using arrow function, the context of 'this' doesn't change (when working with callbacks, ... ).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.