Recently, I encountered an issue with my code where the data selected by the user gets parsed into an array, but there is no way to store this data permanently. As the user navigates away from the component, the data vanishes.
I attempted to utilize Ionic storage to address this problem, but I lack the knowledge on how to implement it effectively.
Here is the snippet of the relevant code.
export class ContactComponentComponent implements OnInit {
constructor(private contacts: Contacts, private storage: Storage) {
this.getContact();
}
mContacts = [
{
id: [0],
name: '',
number: ''
},
{
id: [1],
name : [''],
number: ['']
},
{
id: [2],
name : [''],
number: ['']
},
{
id: [3],
name : [''],
number: ['']
},
{
id: [4],
name : [''],
number: ['']
}
];
ngOnInit() {}
pickContact(contactId) {
this.contacts.pickContact().then((contact) => {
this.mContacts[contactId].name = contact.name.givenName;
this.mContacts[contactId].number = contact.phoneNumbers[0].value;
this.storage.set('contact-name', JSON.stringify(this.mContacts.name));
this.storage.set('contact-number', JSON.stringify(this.mContacts.number));
});
}
getContact()
{
this.storage.get('contact-name').then((val) => {
console.log('Contact Name: ', val);
});
this.storage.get('contact-number').then((val) => {
console.log('Contact Number:', val);
});
}
}
Below is the HTML snippet.
<ion-list>
<ion-grid>
<ion-row>
<ion-col>
<ion-item-group *ngFor="let contacts of mContacts">
<ion-card (click) = "pickContact(contacts.id)">
<ion-item lines = "none">
<ion-label class="ion-text-wrap">Name: {{contacts.name}}</ion-label>
</ion-item>
<ion-item lines = "none" >
<ion-label class="ion-text-wrap">Number: {{contacts.number}}</ion-label>
</ion-item>
</ion-card>
</ion-item-group>
</ion-col>
</ion-row>
</ion-grid>
</ion-list>
I understand that this code might not be the best approach, and I would appreciate any guidance on how to properly save the array after the user selects it and retrieve it when the component is called again.