GluePear
GluePear

Reputation: 7715

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.

Upvotes: 0

Views: 1062

Answers (2)

Make sure your Component is loaded through or using its selector. I made a separate component and forgot to load it in the application.

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657238

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

Upvotes: 2

Related Questions