Scope of Ionic2 Storage Promise.all function

Looking for help with assigning an Ionic2 Storage value to a local variable. When I console.log inside the .then, it works fine, but the value seems to be limited to that function/method only. Most examples I've found demonstrate how to 'get' the data, but don't really show how to apply it to other parts of my code.

-appreciate any assistance

import { Storage } from '@ionic/storage';

export class MyApp {

favDessertMax: string;
favDessertRuby: string;

constructor(storage: Storage) { }

 storage.ready().then(() => {

   this.storage.set('Max', 'Apple sauce');
   this.storage.set('Ruby', 'Banana split');


   Promise.all([
       this.storage.get('Max'),
       this.storage.get('Ruby'),
   ])
     .then(([val1,val2]) => {
       this.favDessertMax = val1; 
       this.favDessertRuby = val1;
       console.log(val1 + " " + val2); //values are accessible here
     })
   console.log(val1 + " " + val2); // values are not accessible outside of the function (or anywhere else)
   });

  storyTime() { // Need value to work here
    let myStory = 'Max likes ' + this.favDessertMax + ' and Ruby Likes 'this.favDessertRuby';
  return myStory;
  }

}

Answer №1

Promise.all is used to set data to a local variable in JavaScript. This process is asynchronous, meaning you may not receive the data immediately when you call the storyTime() function. To ensure that you get the data, you need to chain the promise properly.

getData(){

    return Promise.all([
           this.storage.get('Max'),
           this.storage.get('Ruby'),
       ])
         .then(([val1,val2]) => {
           this.favDessertMax = val1;  // value retrieved from 'Max'
           this.favDessertRuby = val2; // value retrieved from 'Ruby'
           return [val1,val2];//return values within then.
           console.log(val1 + " " + val2); //values successfully displayed here
         })
       });
    }

storyTime() { // Need values to work properly here
    return this.getData().then([val1,val2]=>{
    let myStory = 'Max likes ' + val1 + ' and Ruby Likes ' + val2 + ';
    return myStory;
     });
  }

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

Returning a 'never' type from a function in React using Typescript

Basically, I have a function that initiates the OAuth flow (redirecting to Google OAuth login page, for example): async function signIn() { // start OAuth flow } And let's say I want to use it in a useEffect hook like this: ... useEffect(() => { ...

`ng-apexcharts` causing unit test failures

I've been working on integrating apexcharts and ng-apexcharts into my home component. While I was able to get it up and running smoothly, it seems to be causing issues with my unit tests. Despite researching possible solutions, I haven't been abl ...

angular table cell with a show more/less button

I'm trying to create a button that can hide/unhide text in a table cell if the length is greater than a certain number. However, the current implementation is not working as expected. The button ends up opening all texts in every cell, and it only wor ...

The element did not match the Angular Routing selector "app-home"

How can I prevent my initial component from being loaded twice in Angular? I am trying to implement a default/empty component to avoid the AppComponent being loaded within itself. The empty component would serve as the starting point for loading other comp ...

Compelling users to upgrade to the latest version of the Angular 5 application

My Angular 5 application is currently deployed on Azure using ng build --prod. I am looking for a way to ensure that users are always prompted to download the latest version of the application, including any updates to style sheets. However, I have notic ...

Redirecting to different paths using Angular 6 routing

My experience with Angular is fresh, as I embark on crafting my initial Angular application tailored for an admin dashboard. The task at hand involves setting up two distinct layouts: Authentication layout (incorporating login, logout, forgot-password f ...

Angular does not display a loading indicator in the header

When handling service calls, I have implemented a loading indicator to provide feedback to the user. However, it appears that this indicator is not effectively preventing users from interacting with header items before the loading process is complete. My ...

Tips for selecting objects based on property in Typescript?

Consider this scenario: import { Action, AnyAction } from 'redux'; // interface Action<Type> { type: Type } and type AnyAction = Action<any> export type FilterActionByType< A extends AnyAction, ActionType extends string > ...

Angular: Verify that all services are fully executed before proceeding to the next step

We have adopted Angular for our project. Our component receives data from an API, which is then processed by Data Services. These services transform the data by combining first and last names, rounding dollar amounts, performing calculations, etc. The fina ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

How can I effectively make properties accessible in my template to facilitate form validation in Angular?

Scenario: I'm facing a situation in my Angular project where I have a LoginFormComponent. This component has a form with two properties: email and password. My goal is to create properties within this component that can be accessed in the template. Th ...

Form Validation in Angular Using Async Injection of Services

I am working on a custom async validator within a reactive form that requires validation of name uniqueness by making a call to a service. Due to the purity of validators, I am struggling to find a proper way to inject a provider like HTTP to handle these ...

Entering the appropriate value into an object's property accurately

I am currently facing an issue with typing the value needed to be inserted into an object's property. Please refer below. interface SliceStateType { TrptLimit: number; TrptOffset: number; someString: string; someBool:boolean; } inter ...

What are some methods for extracting the values of keys from an object?

I am facing an issue where I have data collected from a service in the form of an interface type object, but I am unable to find or filter a key within this object. The specific error message I am encountering is: ERROR TypeError: Cannot read property &ap ...

Sorry, I cannot complete this task as it involves rewriting copyrighted content

I recently implemented the useRef hook in my scroll function, specifying HTMLDivElement as the type. However, I encountered an issue where I received the error message "Property 'clientHeight, scrollHeight, scrollTop' does not exist on type &apos ...

How can an Angular 2 component detect a change in the URL?

My Angular 2 component subscribes to a service based on the URL hash without calling any subcomponents. I am wondering if I should use Route or Location for this scenario, and how can I listen for and react to a pop state event? ...

"Angular4 multiple file upload - batch of files cleared for a second round of

I am a beginner with angular I am currently working on implementing multiple file uploads <input #fileInput type="file" multiple="true" ngModel class="form-control" name="image[]" accept="image/png, image/jpeg, image/gif" id="image" (click) ...

Update the disabled state following the onInit event

Currently, I am developing an angular application at my workplace that requires implementing permissions. The backend stores permissions as either 1 or 0, and the frontend queries a service to retrieve the user's permission. If the user lacks permissi ...

Numerous issues persist in Angular 6 related to unresolved errors such as crypto, fs, http, https, net, path, stream, tls, and zlib

Each time I attempt to run my Angular 6 app on localhost, a series of errors pop up that include missing modules like 'crypto'. Though some can be installed, others like 'crypto' are built-in. This is baffling as these folders do not ex ...

Setting Angular 2+ FormGroup value in a child component form using data passed from the parent

As a beginner in coding, I encountered an issue with sharing a form component between an add member and edit member component. While copying the form code into each component works fine, it goes against the DRY principle and could lead to banning from furt ...