Search code examples
javascriptangularobservableangular-services

Angular service not updating subscribed components


I have an Angular 2/4 service which uses observables to communicate with other components.

Service:

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

@Injectable()
export class EventsService {

  subject = new BehaviorSubject<any>(EVENTS);

  getEvents(): Observable<any> {
    return this.subject.asObservable();
  }

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

  search(searchTerm) {
    const newEvents = EVENTS.filter((obj) => obj.event.includes(searchTerm));
    this.subject.next(newEvents);
  }
}

My home component is able to subscribe to this service and correctly updates when an event is deleted:

export class HomeComponent {

  events;
  subscription: Subscription;

  constructor(private eventsService: EventsService) { 
    this.subscription = this.eventsService.getEvents().subscribe(events => this.events = events);
  }

  deleteEvent = (event) => {
    this.eventsService.deleteEvent(event);
  }
}

I also have a root component which displays a search form. When the form is submitted it calls the service, which performs the search and calls this.subject.next with the result (see above). However, these results are not reflected in the home component. Where am I going wrong? For full code please see plnkr.co/edit/V5AndArFWy7erX2WIL7N.


Solution

  • If you provide a service multiple times, you will get multiple instances and this doesn't work for communication, because the sender and receiver are not using the same instance.

    To get a single instance for your whole application provide the service in AppModule and nowhere else.

    Plunker example