How to retrieve a stored value using Ionic 3 native storage

Hey there,

I recently attempted to implement code from the Native Storage plugin documentation found at this link: Native Storage

    import { NativeStorage } from '@ionic-native/native-storage';

constructor(private nativeStorage: NativeStorage) { }

...

this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
  .then(
    () => console.log('Item stored!'),
    error => console.error('Error storing item', error)
  );

this.nativeStorage.getItem('myitem')
  .then(
    data => console.log(data),
    error => console.error(error)
  );

Upon launching my android simulator device, the console outputs the following:

[00:02:01]  console.log: Item stored!
[00:02:01]  console.log: [object Object]

https://i.sstatic.net/qYTKh.png

I am currently seeking a solution to retrieve the stored information. My goal is to leverage data stored in the native storage for conditional logic on another page, but I am facing challenges with retrieval. For instance, I intend to execute a function if the value of "Vibrator" stored in native storage is true. Can anyone provide guidance on how to achieve this?

Appreciate your support!

Answer №2

Attempting to obtain the value in this manner is not effective due to it being an Async operation. Merely attempting to copy/paste the code from the documentation is not a practical use case. It serves only as an example.

For a more realistic scenario, consider following this example for storing the value:

my-storage-page.ts

this.myStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
  .then(
    () => console.log('Item successfully stored!'),
    error => console.error('Error while storing item', error)
  );

Subsequently, on another page or component, you can retrieve the stored value with the following snippet:

my-retrieval-page.ts

this.myStorage.getItem('myitem')
  .then(data => {
      console.log(data);
   },
    error => console.error('Error retrieving data', error)
  );

Note: If you require additional assistance, do not hesitate to reach out.

Answer №3

I followed your instructions precisely by adding the desired property value in "property". I inserted the code into Home.ts

this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
  .then(
    () => console.log('Item stored successfully!'),
    error => console.error('Error storing item', error)
  );

In addition, in the file parameter.ts, I included:

this.nativeStorage.getItem('myitem')
  .then(
    data => console.log(data.property),
    error => console.error(error)
  );

Upon running the simulator, I observed the following outputs on the console when transitioning between Home.ts and parameter.ts:

[10:30:06]  console.log: Item stored successfully! 
[10:30:06]  console.log: deviceready event has not fired after 5 seconds. 
[10:30:06]  console.log: Ionic Native: deviceready event fired after 4017 ms 

[10:56:17]  console.log: value 
[10:56:17]  console.error: [object Object]

I am pleased to see that I was able to retrieve the value of the "property", which is indeed "value".

Thank you for your assistance!

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

Having difficulty converting string columns/data to numerical values when exporting an Ag-Grid table to Excel with getDataAsExcel function

I am having an issue with exporting data from my ag-grid table to excel using the API method getDataAsExcel. The problem arises because I have a column containing only string values, while all other columns are numeric and displayed in the ag-grid table a ...

End the primary division post button activation within Angular 2

Is there a way to close the main div upon clicking a button that is located inside the same div? Below is my code snippet: index.html <div id="main"> <button type="button">Click Me!</button> </div> hello.component.ts import ...

Does Typescript fail to recognize the "delete" operator?

Whenever I utilize the delete operator in Typescript, it appears that the system does not recognize that the property has been eliminated. For instance: interface HasName { name: string; } interface HasNoName { name: never; } function removeName( ...

Navigating with Angular 2 [routerLink] while including route parameters

Currently, I am working on developing an application using angular 2. As part of this project, I am trying to pass parameters to the [routerLink] tag in order to create a link structure like the following: <a href="/auth/signup?cell=1654654654">< ...

Error: Unable to locate bundle.js when attempting to refresh the page with a specific ID in the URL

I encountered an issue where I tried redirecting a user to their profile page to display the profile information corresponding to it. Let's say we have http://localhost:8080/user/1 as an example. Upon redirecting the user using the navbar link, the pa ...

Using Angular2, you can easily implement property binding on child elements

Consider this basic Angular 2 application Primary component: @Component({ selector: "app" }) @View({ directives: [ChildComponent] template: '<child-component></child-component>' }) export class App {} Child component @ ...

Module 'rxjs/internal/Observable' not found

When attempting to utilize the JwtHelperService module in my service, I encountered the following error: ERROR in node_modules/@auth0/angular-jwt/src/jwt.interceptor.d.ts(3,28): error TS2307: Cannot find module 'rxjs/internal/Observable'. In my ...

Displaying the Ionic loading spinner on the entire page rather than a restricted small box

Right now, I'm able to implement a basic loading effect, but it appears as a small box. presentCustomLoading() { let loading = this.loadingCtrl.create({ content: 'Loading Please Wait...' }); loading.present(); } However, I ...

Enable child classes to overwrite using either a function attribute or a method

class Foo { foo: () => void } class Bar extends Foo { foo() {} } Is there a way in which TypeScript can be configured to allow the scenario described above? Playground The 'Foo' class defines a property 'foo' as an instance ...

What is the best way to create varying DOM elements in Angular according to JSON attributes?

In order to enhance user experience, my application includes a feature that presents release notes to users whenever a new version of the app is deployed. These release notes are stored in JSON format in the backend, structured as follows: { "version" ...

How can you define the types of function arguments when destructuring arguments in TypeScript?

TS throws an error that states: Error:(8, 20) TS7031: Binding element 'on' implicitly has an 'any' type. Error:(8, 24) TS7031: Binding element 'children' implicitly has an 'any' type. Below is the function I am wor ...

The Angular functionality is functioning correctly on Mozilla browsers, but encountering issues on Chrome

I am looking to create a convenient page on my website for my team to easily access and copy the email template I have created to send to clients. The process would involve them visiting this page, clicking a button, and then pasting the email template dir ...

"Exploring the capabilities of Angular 4 Material for seamless page navigation

I am brand new to Angular 4 using Material Design 2. I have a simple inquiry regarding this topic. My code is in app.component.html, which displays a few mat-card components. When clicking on any link inside the mat-card component, it should switch the e ...

Custom Angular directive for collapsing sub menus with CSS

I found a helpful article on creating collapsible menus and submenus using only Bootstrap and custom code for Angular 2, 4, 5, 6. I've been able to implement the logic successfully, but I'm facing an issue with multiple menus where clicking on an ...

Exploring the use of .pipe with Angular Jest for testing

Currently, I am trying to test the following .ts file: create(entityResourceID, params: any): Observable <any>{ const url = `${this.apiUrl}/${entityResourceID}/assignee`; return this.http.post(url, params).pipe( map(() ...

Errors occur with Metro bundler while utilizing module-resolver

Recently, I completed a project using the expo typescript template that runs on both iOS and Android platforms, excluding web. To enhance my development process, I established path aliases in the tsconfig.json file as shown below: "paths": { "@models/ ...

Expanding Generic Interfaces in Typescript

I am working on a project where I need to enhance a typescript type by adding a new property in order to extend a generic type. To achieve this, I plan to define a Confidence<any> type that has the following structure: export interface Confidence< ...

The scrollbar track has a habit of popping up unexpectedly

Is there a way to prevent the white area from showing up in my divs where the scroll bar thumb appears? The issue seems to occur randomly on Chrome and Safari. https://i.sstatic.net/jFzTf.png This is the div in question .column-content{ height:60vh; ...

"Encountering a TypeScript error when using React Query's useInfiniteQuery

I am currently utilizing the pokeApi in combination with axios to retrieve data import axios from 'axios' export const fetchPokemonData = async ({ pageParam = "https://pokeapi.co/api/v2/pokemon?offset=0&limit=20" }) => { try ...

Troubleshooting: Issues with Angular 2 Cross-Domain Calls on Local Servers

My Angular 2 application is currently running on port 8100, while the API project built using Node and Express is running on a different port 3003. It is important to note that the API project is not a typical REST API. When attempting to call one of the ...