Leverage Ionic storage data in a separate function

Currently working on developing a new APP using Ionic.

Here is the structure of a service I am using:

import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable, of } from "rxjs";
import { catchError, tap } from "rxjs/operators";
import { environment } from "src/environments/environment";
import { Storage } from "@ionic/storage";

@Injectable({
  providedIn: "root"
})
export class myservice {

  serverUrl = environment.baseUrl;

  httpHeader = {
    headers: new HttpHeaders({ "Content-Type": "application/json" })
  };

  userid: number;

  constructor(private http: HttpClient, private storage: Storage) {
  }

  async getFromStorageAsync(){
      await this.storage.get('userid').then((val)=>{
        this.userid = val;
        console.log("UserId", this.userid); 
      });
      console.log("UserId", this.userid); 
  }

  use_storage_data() {
    this.getFromStorageAsync();
    console.log("Userid",this.userid); 
    let postData = {
      userid: this.userid,
      username: "samplename"
    };
    return this.http
      .post<any>(this.serverUrl + "/appdata.php", postData)
      .pipe(catchError(this.handleError));
  }

}

When calling the service on a page, it is done like this:

  getData(){
    this.myservice.use_storage_data().subscribe(data => {
     // console.log(data);
    });
  }

I am looking for help in making storage data a global variable or suggestions on a better approach to manage and utilize user id and user name data in an Ionic app.

NOTE: User id is successfully set when a user logs in.

Thank you.

Answer №1

When working with asynchronous methods like Future, the userId variable may initially be undefined due to the nature of these operations happening in the background while other processes are ongoing...

The userId value will eventually be updated at some point in the future. To handle this scenario in your code, you need to incorporate a .then statement in your method. This way, whenever a value is retrieved from an asynchronous function, the userId variable will be updated...

Here's a snippet of the code...

use_storage_data() {
    this.getFromStorageAsync().then(val => console.log(val)); //userId will be defined here
    // Now you can do the following:
    this.getFromStorageAsync().then((id){
      console.log("Userid", id); // userId defined
    if(id){
    // To prevent capturing any initial undefined value of userId
    let postData = {
      userid: this.userid, // userId is currently undefined
      username: "samplename"
    };
    return this.http
      .post<any>(this.serverUrl + "/appdata.php", postData)
      .pipe(catchError(this.handleError));
    });
    }
    
  }

I hope this clarification helps you understand the concept better.

Answer №2

I have made a change in how I retrieve data from storage.

First, on the page, I import the following:

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

Next, I retrieve the value from storage and pass it to a service:

 getData(){
    this.storage.get('userid').then((val)=>{
      this.myservice.use_storage_data(val).subscribe(data => {
        console.log(data);
      });
    });
  }

This method works perfectly for me.

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

Encountering Issue: Unable to locate control with the given name in Angular when generating Dynamic Form with FormGroup

As a beginner in Angular, I aim to develop a dynamic Survey Form that can adjust its questions and input types based on the area. These changes are fetched as JSON data through API calls. Here is the relevant code snippet: .ts File export class Maintenan ...

Angular 7 Material: How to perfectly center align your cards side by side

When I have an abundance of material cards, they tend to align vertically. Is there a way to align the cards horizontally from left to right instead? ...

Encountering a service call error during the execution of Angular 2 unit tests using Jasmine

Struggling with testing an angular service, my TypeScript code seems correct but I keep getting an error in my test cases for "this.someFunction.show()" not being a function, even though it exists in my actual service. Here is what I'm attempting to d ...

Problematic Angular 6 Lazy Loading Situation

Below is the code snippet I am using for lazy loading: const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'manager', lo ...

Utilizing Angular 2: Implementing a template-driven form to send data from a chosen element to the submitting object

Hey there! I'm fairly new to Angular 2 and have been trying to tackle this issue for a while now. I have a user object that contains another nested object, defined by the User interface: export interface UserModel{ name: string, service: Service ...

typescript code may not display a preview image

I recently came across a helpful link on Stack Overflow for converting an image to a byte array in Angular using TypeScript Convert an Image to byte array in Angular (typescript) However, I encountered an issue where the src attribute is not binding to t ...

Tips for updating the selected option in a nested reactive form in Angular?

Class User is defined as follows: export class User { name: string details: Details; } Class Details is defined as follows: export class Details { country: Country; major : Major; } Class Major is defined as follows: export class Major{ department : st ...

Linking to a variable that could potentially be non-existent

How can I properly bind to myVariable even if it may not be present? (myVariable comes from a service that may not always be active) <input pInputText type="text" [size]="size" [value]="myVariable" style="cursor: poin ...

Issue with PrimeNG dropdown where selected option gets reset when bound to interface property

Here is how I have implemented the p-dropdown: <p-dropdown name="taxOptions" [options]="taxOptions" [(ngModel)]="purchaseInvoiceDetail.tax"></p-dropdown> The values for the taxOptions property are set like this: this.taxOptions = [ { l ...

Encountering an issue while adding types to a custom component in a Formik form: Error message states that type 'T[keyof T]' cannot be assigned to type 'string'

I'm delving into TypeScript for the first time and attempting to incorporate it into a previous project as a learning exercise. I've hit a roadblock while trying to add types to a custom form field component in Formik, encountering an error mess ...

Struggling with extracting an array of objects from a JSON file and accessing individual attributes within each object?

As a newcomer to Typescript, I am eager to work with JSON and access its objects and attributes. However, I am encountering difficulties in achieving this. I have attempted using functions like 'for of' and 'for in', but unfortunately, ...

The footer moves upwards when a file is downloaded

I am facing an issue with my website footer and its CSS styling. #footer { position: absolute; bottom: 0; width: 100%; height:8rem; } The main goal is to keep the footer at the bottom of the page, regardless of the amount of content on th ...

Angular Rxjs repeatWhen: when none of the statuses are COMPLETED

If the status in my Angular Service file is not 'COMPLETED' for all data, I need to retry hitting the same URL up to 5 times with a delay of 5 seconds. [ { "data": [ //SET OF OBJECTS ], "status": ...

Adjust google maps to fill the entire vertical space available

I found this helpful resource for integrating Google Maps into my Ionic app. Everything is working smoothly, but I am trying to make the map fill the remaining height below the header. Currently, I can only set a fixed height in pixels like this: .angula ...

Showing information from a JSON file in a layout

Hey there! I could really use some assistance in displaying my data. So, I've got this custom provider that calls my API, and everything is running smoothly. Currently, I'm focusing on the page titled 'playing', and here's a glim ...

Updating a property in React by fetching data from API and storing it in the cache

Recently, I implemented nanoid to generate unique IDs for my NBA team stat tracker app. However, upon browser refresh, the fetch function generates new IDs for each team stored in the favorites list. This causes the app to fetch data again and assign a new ...

FInding the inner value of a Vuetify chip

I have a Vue application that utilizes Vuetify chips to display information. I'm trying to log the value inside a specific chip when it is clicked, but I keep getting an undefined error when trying to access the array where the information comes from. ...

Issue with saving component value using Angular's *ngIf directive in Ionic 3

I have created Angular components in Ionic 3 and implemented multiple div tabs using the *ngIf directive. I can successfully switch between tabs using buttons. However, a problem arises when I navigate to another section of the main HTML page containing t ...

What is the solution for resolving this Angular issue: Expected argument expression.ts(1135)?

While following a CRUD tutorial, I encountered an issue with the code. Even though I have verified that my code matches the tutorial's code, I am getting an error message saying "Argument expression expected. ts(1335)" in the submit method onSubmit(). ...

The 'target' property is not found on the specified 'string' type

I've encountered an issue while creating a search bar in Typescript. Despite my efforts, the input is not being recognized. It seems that whenever I use the term 'target' in my onChange method, it triggers an error stating: Property &ap ...