What is the most common method to inform the ListItemPage that its items
variable needs to be updated?
If you have a service already related to the items (such as a service fetching items from the backend), using Observables would ensure consistency.
@Injectable()
export class YourItemsService {
public onItemsChange: Subject<any> = new Subject<any>();
// ...
public changeItems(someParam: any): void {
// ...
// Notify subscribers about the new data
this.onItemsChange.next(newItems);
}
}
This way, each page can subscribe to it and get updated when there are changes in the data. Pages can also utilize the same service to modify the data, knowing that the change will be reflected across all subscribed pages:
@Component({
selector: 'another-page',
templateUrl: 'another-page.html'
})
export class AnotherPagePage {
constructor(private yourItemsService: YourItemsService) {}
updateItems(data: any) {
// Use the service to modify the data, keeping everyone updated
this.yourItemsService.changeItems(data);
}
}
And...
@Component({
selector: 'some-page',
templateUrl: 'some-page.html'
})
export class SomePagePage {
private itemsChangeSubscription: Subscription;
constructor(private yourItemsService: YourItemsService) {
// Subscribe to changes in the items
this.itemsChangeSubscription = this.yourItemsService.onItemsChange.subscribe(data => {
// Update the data of the page...
// ...
});
}
ionViewWillUnload() {
// Clear the itemsChangeSubscription
this.itemsChangeSubscription && this.itemsChangeSubscription.unsubscribe();
}
}
Why follow this approach? If you need to perform certain actions every time the items are changed (like updating a total amount in another service or any other property), centralizing that logic in the service is beneficial. Each page can focus on handling the new data to update its current state, while letting the service handle other changes
If you choose not to use observables for some reason (lack of a centralized service, creating a new one specifically for a single event seems unnecessary), you could opt for Ionic's Events.
In such cases, if custom logic needs to be executed each time an event is triggered, that code would need to be duplicated on every subscribing page.
More details on Ionic's events
Inspecting Ionic's Events implementation (source code) reveals that internally Ionic uses an array to store callbacks for execution upon publishing of events, rather than implementing Observables.