Currently, I am implementing local storage for my Ionic application. While I can successfully add and retrieve data from local storage, I encounter an issue when trying to delete a specific object - it ends up removing everything in the database. Moreover, attempting to add a new object to the now empty database results in the following error message: "Runtime error - Cannot read property 'push' of undefined"
The intended user scenario for the app involves a user adding a favorite TV show to a favorites list and having the option to unfavorite it if desired.
Below is the code snippet from my service that contains the functions for handling local storage:
export class FavoritesService{
constructor(private storage: Storage){}
public favoritesSeries: any = [];
addSeriesToFavorites(serie: any)
{
this.favoritesSeries.push(serie);
console.log('Add to');
console.log(this.favoritesSeries);
this.storage.set('FavSerie',this.favoritesSeries);
}
getFavoriteSeries(){
this.favoritesSeries = [];
this.storage.get('FavSerie').then((val) => {
console.log(val);
if (val){
this.favoritesSeries = val;
}});
}
removeFavoriteSeries(){
this.storage.remove('FavSerie').then((val)=>{
this.favoritesSeries = val
console.log('serie is removed');
});
}
saveChanges(favoriteSeries: any) {
this.favoritesSeries = favoriteSeries;
this.storage.set('favoriteSeries', this.favoritesSeries);
}
}
The favorites page code snippet:
export class Favorites {
series: {};
constructor(public navCtrl: NavController,
public navParams: NavParams,
public seriesService: SeriesService,
public alertCtrl: AlertController,
public favoritesService: FavoritesService) {
}
ionViewDidLoad() {
//displays the favorite series
this.series = this.favoritesService.favoritesSeries;
console.log(this.favoritesService.favoritesSeries);
console.log(this.series);
}
onRemoveFromFavorites(FavSerie: any){
const alert = this.alertCtrl.create({
title: 'Remove From Favorites',
subTitle: 'Are you sure?',
message: 'Are you sure you want to remove from favorites?',
buttons: [
{
text: 'Yes',
handler: () => {
console.log('OK');
console.log(FavSerie);
this.favoritesService.removeFavoriteSeries();
console.log('after service addToFavorite');
}
},
{
text: 'No',
role: 'cancel',
handler: () => {
console.log('Cancel');
}
}
]
});
alert.present();
}
}