Async retrieval of values from Ionic storage

I am facing an issue where I need to retrieve two values stored in Ionic storage, but the values are retrieved asynchronously causing the request to happen before the values are fetched.

The values for Auth and url are stored in Ionic storage.

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import {Headers} from '@angular/http';
import { Storage } from '@ionic/storage';

/*
  Processor for SeasonService provider.

  Visit https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more details on providers and Angular 2 DI.
*/
@Injectable()
export class SeasonService {
Auth;
url;

  constructor(public http: Http, public storage: Storage) {
    console.log('Inside SeasonService constructor');

    this.storage.get('Auth').then((Auth) => {
      console.log('Retrieved Auth value is', Auth);
      this.Auth = Auth;

    } );
    this.storage.get('url').then((url) => {
      console.log('Retrieved url value is', url);
      this.url = url;
    } );
   }

  public getSeasonList() {

          console.log('Season Auth value is', this.Auth);
          console.log('Season url value is', this.url);
        const headers: Headers = new Headers();
        headers.append('Authorization', 'Basic ' + this.Auth);
        headers.append('Content-Type', 'application/json');
        return (this.http.get('http://' + this.url +'/Windchill/servlet/rest/rfa/instances?module=SEASON',
        {headers: headers}).
        map((response: Response) =>  response.json()));
      }
}

This is how the Output appears:

Here
auth-service.ts:49 Headers {_headers: Map(2), _normalizedNames: Map(2)}
auth-service.ts:77 There
season-service.ts:19 Inside SeasonService constructor
season-service.ts:34 Season Auth value is undefined
season-service.ts:35 Season url value is undefined
season-service.ts:22 Retrieved Auth value is d2NhZG1pbjp3Y2FkbWlu
season-service.ts:27 Retrieved url value is 192.168.146.52
auth-service.ts:79 Your CSRF token is laxYnd5XE6d/r+W655087+8dY5Irxc7do94fxLgvY5ImgNeIwsgI1bYaQdAzxZDM5sMZsqgbXppFntGDoJhrq+puJJROnN+N1MEcy7d4Js8ozs7Oxpwfpe0zRvcIktg=
auth-service.ts:82 Your Authorization key is d2NhZG1pbjp3Y2FkbWlu
auth-service.ts:85 Your URL is 192.168.146.52

Answer №1

Ensure you wait for both promises to be resolved before making a request. Move your storage code to an init method.

public init(){

let promiseList: Promise<any>[] = [];
promiseList.push(
 this.storage.get('Auth').then((Auth) => {
      console.log('Retrieved Auth is', Auth);
      this.Auth = Auth;

    } ));
promiseList.push(
    this.storage.get('url').then((url) => {
      console.log('Retrieved URL is', url);
      this.url = url;
    } ));

return Promise.all(promiseList);
}

Call the init method before calling getSesonList as shown below:

this.sessionService.init().then((values)=>{
this.sessionService.getSeasonList();
});

This will ensure that the getSeasonList method is only called after both storage promises are resolved successfully.

Remember to implement some error handling code as needed.

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

Why isn't my ajax success data showing up in AngularJS?

Currently, I am working on calling ajax to retrieve my HTML content. However, I am encountering an issue when trying to display that data in a tooltip or popover. Even though I can see the data in the console, the tooltip is showing up as black. I am not s ...

Sorting through an array of objects based on TypeScript's union types

My array consists of objects such as: array = [{name: 'something'}, {name: 'random'}, {name: 'bob'}] I have created a union type type NamesType = 'something' | 'bob' Can the array be filtered based on t ...

A guide on organizing similar elements within an array using Angular

Could you assist me in grouping duplicate elements into separate arrays of objects? For example: array = [{key: 1}, {key: 5}, {key: 1}, {key: 3}, {key: 5}, {key: 1}, {key: 3}, {key: 2}, {key: 1}, {key: 4}]; Expected output: newArrayObj = {[{key: 1}, {key ...

Utilizing Ionic to seamlessly integrate Firebase into a factory, maintaining separation of controllers and services within distinct files

I'm struggling with setting up a firebase factory for use in my controllers. Currently, this is how my code appears: index.html ... <!-- integrating firebase --> <script src="lib/firebase/firebase.js"></script> <script src="lib/ ...

Using TypeScript to Verify the Existence of Words in a String

Is there a way in typescript to find specific words within a given string? For example: If we have a list: ['Mr', 'Mrs', 'FM.', 'Sir'] and a string named 'Sir FM. Sam Manekshaw'. The words 'Sir' ...

What is the best way to rid ourselves of unwanted values?

In the laravel-vue-boilerplate package, there is a User CRUD feature. I duplicated this functionality to create an Item CRUD by making some changes and adjustments. Everything is working fine except for one issue: after editing an item, when trying to add ...

Use Ramda to convert an array of objects into nested objects

As a beginner, please forgive me for asking what may be considered a naive question. I currently have an array of objects const arr = [{id: 1, name: 'Pete'}, {id: 5, name: 'John'}, {id: 3, name: 'Peter'}] and I am looking to ...

Learn how to capture complete stack traces for errors when using Google Cloud Functions

In the codebase I am currently working on, I came across a backend service that I would like to utilize for logging all errors along with their corresponding Http statuses. If possible, I also want to retrieve the full stack trace of these errors from this ...

The ngOnChanges method fails to exhibit the anticipated modifications in a variable

Trying to grasp the concept of the ngOnChanges() callback, I created an example below. Despite having values for the attributes title and content in the Post interface during compile time, I do not see any logs from ngOnChanges. Please advise on the corre ...

In the context of React Typescript, the term 'Component' is being mistakenly used as a type when it actually refers to a value. Perhaps you intended to use 'typeof Component' instead?

Looking to create a routes array and apply it to useRoutes in react-router@6. I am currently using TypeScript and Vite. However, I encountered an error when attempting to assign my component to the 'element' key. type HelloWorld = /unresolved/ ...

In what scenarios is it most beneficial to utilize an isolate scope in Angular?

The AngularJS guide states that the isolate scope of a directive isolates everything except models explicitly added to the scope: {} hash object. This is useful for building reusable components because it prevents unintended changes to your model state, al ...

Exploring the process of defining a generic type for a function which accepts any Static Model and outputs instances of that Model using Sequelize

My task involves defining a function named FieldSearch with specific parameters: fieldSearch<SpecificModel extends Model>( model: ModelStatic<SpecificModel>, // Struggling with this part fields: Array< attributes of the static model p ...

Using Next.js, it is not possible to use absolute imports within SASS

Having trouble utilizing @/ imports within my scss files. The variables I need are stored in src/styles/_variables.scss Here is my tsconfig.json: { "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"], "baseUrl": ".", "allowJs": tr ...

In the process of developing a custom Vue component library with the help of Rollup and VueJS 3

My goal is to develop a custom Vue component library using rollup and Vue.js. The process went smoothly with Vue2, but I encountered issues parsing CSS files with Vue3. To address this, I updated the dependencies in the package.json file. package.json { ...

Typescript's Accessor decorator ensures that the decorated code is executed only once, fetching the previously calculated value for any subsequent calls

The topic discussed here originates from a previous discussion on a method decorator in Typescript. In some scenarios, there are `get` methods in a Typescript class that involve intensive computations. Some of these methods always return the same result an ...

Encountering a 404 error when importing http/server in deno

The file named index.ts is located below import { serve } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c3c4d4f0809e8186869e80">[email protected]</a>/http/server.ts"; function ...

Encountered a TypeScript error: Attempted to access property 'REPOSITORY' of an undefined variable

As I delve into TypeScript, a realm unfamiliar yet not entirely foreign due to my background in OO Design, confusion descends upon me like a veil. Within the confines of file application.ts, a code structure unfolds: class APPLICATION { constructor( ...

Error: In Angular and Typescript, the function this.$resource is not recognized

I keep encountering a TypeError: this.$resource is not a function. Below is the code snippet causing the issue: export class DataAccessService implements IDataAccessService { static $inject = ["$resource"]; constructor(private $resource: ng ...

What is the process of defining a TypeScript AWS Lambda handler for Lambda Function URLs?

The npm package @types/aws-lambda provides TypeScript declarations for different ways Lambda functions can be triggered. For instance, when triggering the Lambda function through API Gateway, you can use the following code snippet: import { APIGatewayProxy ...

Tips for properly passing a Vue3 Ref variable as a reference (plus the mystery of the "global" variable)

I created a custom Quasar/Vue3 component called TemperatureOutside.vue: <template> <div class='text-large-1 text-weight-bold'> {{ temperature }}° </div> </template> <script setup lang='ts'> import ...