Exploring the versatility of Angular/Ionic Storage for dynamic data storage

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.

Answer №1

After much exploration, I stumbled upon a solution, May this assist someone in need.


  constructor(private contacts: Contacts, private storage: Storage) {
   this.getContact();
  }
  key:string = "contacts";
  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.saveContacts();
    });
  }
  saveContacts(){
    this.storage.set(this.key, JSON.stringify(this.mContacts));
  }
  getContact()
  {
    this.storage.get(this.key).then((val) => {
      console.log('Contact Name: ', val);
      if (val != null && val !== undefined) {
        this.mContacts = JSON.parse(val);
      }
    });

  }


}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When faced with the error message "Typescript property does not exist on union type" it becomes difficult to assess the variable

This question is a continuation of the previous discussion on Typescript property does not exist on union type. One solution suggested was to utilize the in operator to evaluate objects within the union. Here's an example: type Obj1 = { message: stri ...

Tips on showcasing lengthy string content from JSON in a structured list format using react with typescript

Is there a way to display long string data from a JSON file in a list format when the description string is too lengthy? How can I split or format the description using React and TypeScript? The JSON data I have is as follows: "options": [ ...

Encountering the issue of receiving "undefined" in node.js after submitting data from an Angular form

I am facing an issue where I am getting 'undefined' in the backend (node.js) when I submit data from angular forms, even though I have used body-parser to parse the incoming data. server.js const express= require("express"); const app= ...

In Angular, you can easily modify and refresh an array item that is sourced from a JSON file by following these steps

Currently, I am working on implementing an edit functionality that will update the object by adding new data and deleting the old data upon updating. Specifically, I am focusing on editing and updating only the comments$. Although I am able to retrieve th ...

Update the icon in real-time based on the text with Angular 8 and Font Awesome, achieving dynamic changes effortlessly

I need to dynamically change the icon based on the value within a span element. Here is the HTML structure: The version text will only have two possible values: If the value is "Active", then a success icon should be displayed. If the value is "Inactive ...

Alert: VirtualizedList warns of slow updates for a large list despite optimized components

Struggling with avoiding the warning message "VirtualizedList: You have a large list that is slow to update" while utilizing the <FlatList> component in React-Native. Despite thorough research and attempts at finding a solution, including referencin ...

An unassigned variable automatically sets the disabled attribute to true on an input field

Is this behavior a problem or normal? Consider the following form structure: <form #form="ngForm" > <div> <label>field1</label> <input type="text" name="field1" [(ngModel)]="mainVar" [disabled]="someVar" /> ...

I keep encountering an unhandled error while attempting to start the node server

Hi there! I'm diving into the world of node.js and I've run into a problem that has me stumped. I went ahead and installed all the necessary dependencies, but when I try to kickstart the server with the command "node server", I encounter the foll ...

Unexpected results can occur when using ngClass and CSS with all unset

Within my Angular 4 project, I am utilizing ngClass on an object that contains a CSS class applied with unset: all within it. Despite knowing that ngClass adds its properties, the expected result was for all values to be unset and the style elements from n ...

An unexpected token was discovered by Jest: export { default as v1 } when using uuid

While working on writing Jest tests for my React component in a Monorepo, I encountered an error while running the Jest test. ● Test suite failed to run Jest encountered an unexpected token... ...SyntaxError: Unexpected token 'export' ...

Is ngClass failing to activate a class upon clicking?

I am having trouble displaying the activated class as active. It briefly switches to that class and then reverts back. Here is what I have tried: <ion-row > <ion-col col-3 (click)="deviceType('Light')" ><div class="c ...

Encountering issues with loading series on Highchart in Angular 4 due to duplication restrictions

I recently integrated highchart into my Angular 4 application, but I encountered a problem where the same series is being loaded twice. The issue seems to be related to the addSeries method, which is triggered by the @Input() set stressTestResults declarat ...

Angular application code modifications do not reflect in the browser

After making changes to the HTML file of an Angular component, the browser does not reflect those changes when connected to localhost. Even though the old string is no longer present in the project, the browser continues to display it. Interestingly, openi ...

Highly Transferable Angular Modules for 'ng-cli'

I am managing a system with multiple Angular applications built using the ng-cli: FrontendLibs @company/ core/ src/ package.json index.ts main-app/ src/ package.json In this scenario, I have two Angular applications name ...

Navigational bar mishaps: troubleshooting the "is not a function error" in layout.tsx

I recently started learning React (Next.js) and I'm working on adding a navbar feature to my project. The goal is to have the active navlink stand out when the user is on the corresponding page. To achieve this, I created a function that updates the s ...

Testing a component in Angular 2 that utilizes the router-outlet functionality

I recently set up an angular 2 project using angular-cli. As part of the setup, I created a separate AppRoutingModule that exports RouterModule and added it to the imports array in AppModule. Additionally, I have the appComponent which was generated by an ...

Attempting to compile TypeScript by referencing ng2-bootstrap using Gulp within Visual Studio

I've been struggling with this issue for a few days now, and I'm really hoping someone can help me out. Currently, I am experimenting with Angular2 in an aspnet core project. The setup involves using a gulpfile.js to build .ts files and transfer ...

Using Observables in Angular 2 to send polling requests

I have the following AngularJS 2 code snippet for polling using GET requests: makeHtpGetRequest(){ let url ="http://bento/supervisor/info"; return Observable.interval(2000) .map(res => res.json()) //Error here ...

Can Angular Flex support multiple sticky columns at once?

I am trying to make the information columns in my angular material table stay sticky on the left side. I have attempted to use the "sticky" tag on each column, but it did not work as expected. <table mat-table [dataSource]="dataSource" matSort class= ...

Utilize array mapping to alter the complete object

In my project using TypeScript (Angular 2), I am working on creating a "reset" method for an object array: cars [ { id: 1, color: white, brand: Ford, model: Mustang, ... }, ... ] Users have the ability to modify these objects, ...