When validating storage content, session value appears as null

I have been working on developing an Ionic app that requires creating a session for user login. The goal is to store the user's name upon logging in, so it can be checked later if the user is still logged in. I have created a model class and a user class for this purpose. However, I encountered an issue where the value stored inside Ionic returns null when I try to console log it, as shown in the image below:

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

I am puzzled by why it logs like '0: 'n', 1: 'o', 2: 'm', 3: 'e'. My goal is to store the username in the session and log it simultaneously.

Here is how I am implementing this:

import { Storage } from "@ionic/storage";
import { Injectable } from '@angular/core';
import { Usuario } from "./interface/usuario";

@Injectable()
export class Session {

    constructor(public storage: Storage){}

    create(usuario: Usuario) {
        this.storage.set('usuario', usuario);
    }

    get(): Promise<any> {
        return this.storage.get('usuario');
    }

    remove() {
        this.storage.remove('usuario');
    }

    exist() {
        // code snippet
    }
}

User Class Definition:

import { Model } from './../models/model';

export class Usuario extends Model{
    nome: string;
    email: string;
    login: string;
    senha: string;
} 

Model Class Definition:

// code snippet  

Here is where I retrieve the data stored in the Usuario object and log it:

ionViewDidLoad() {
  // code snippet
}

Edit: This is what happens when I console.log inside create method using storage.get:

https://imgur.com/a/W2rQhd8

    create(usuario: Usuario) {
        this.storage.set('usuario', usuario);
        console.log('[TEST] VALUE BEING PASSED IS ', this.storage.get('usuario'));
    }

Answer №1

Let me break down the situation:

  • The file login.ts contains the line:
    this.usuario = new Usuario('nome');
  • The class Usuario inherits from Model.
  • Within the Model class, there is a call to object.assign() which uses the parameter from the constructor to set its own parameters.
  • A string can be seen as an array of characters.
  • Hence, by executing object.assign(this, 'nome'), you are essentially creating parameters based on each character in the string.

Evidently, there seems to be a need for a different approach regarding that specific line of code, perhaps by passing item instead into the constructor. It is important to note that relying solely on object.assign could potentially lead to issues, so it would be wise to provide more explicit instructions for the deserialization process of your data.

export class Usuario {
    nome: string;
    email: string;
    login: string;
    senha: string;

    constructor(src: any) {
        if (src) {
            this.nome = src['nome'] || undefined;
            this.email = src['email'] || undefined;
            this.login = src['login'] || undefined;
            this.senha = src['senha'] || undefined;
        }
    }
}

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

Updating Angular 9 Reactive Form: How to Use PatchValue with a Nested FormArray in a FormGroup

I am currently working on maintaining an existing project that involves using a FormGroup helper to transform data into the FormGroup format. The FormGroup includes four nested FormArray elements, and my task is to update all the data within the FormGroup ...

Understanding the differences between paths and parameters of routes in express.js

My express application has the following routes: // Get category by id innerRouter.get('/:id', categoriesController.getById) // Get all categories along with their subcategories innerRouter.get('/withSubcategories', categoriesControll ...

A guide on simulating x-date-pickers from mui using jest

I have successfully integrated a DateTimePicker into my application, but I am facing an issue with mocking it in my Jest tests. Whenever I try to mock the picker, I encounter the following error: Test suite failed to run TypeError: (0 , _material.gen ...

Angular HTTP client implementation with retry logic using alternative access token

Dealing with access tokens and refresh tokens for multiple APIs can be tricky. The challenge arises when an access token expires and needs to be updated without disrupting the functionality of the application. The current solution involves manually updati ...

Ways to steer clear of utilizing subscriptions and BehaviorSubject.value through a declarative method within rxjs

As I refactor my Angular application, my goal is to eliminate all subscriptions and rely solely on the async pipe provided by Angular for a declarative approach instead of an imperative one. I encounter difficulties implementing a declarative approach whe ...

Encountering Issues with TypeScript Strict in Visual Studio Code Problems Panel

I have discovered that I can optimize my TypeScript compilation process by utilizing the --strict flag, which enhances type checking and more. Typically, I compile my TypeScript code directly from Visual Studio Code with a specific task that displays the c ...

"Encountering a Problem with Rendering the Datetime Picker Component in Angular

When using material-components/[email protected] with angular 14, I encountered an issue where the calendar popup sometimes renders out of place (see image below). Initially, I suspected it to be a cache problem and tried refreshing the page, which te ...

Exploring Angular 2 Tabs: Navigating Through Child Components

Recently, I've been experimenting with trying to access the HTML elements within tabs components using an example from the Angular 2 docs. You can view the example here. Here is a snippet of my implementation: import {Component, ElementRef, Inj ...

Stop the inclusion of the scrollbar in the mat-drawer-inner-container within the Angular mat-drawer Component

Background Story: Working on designing a screen layout that includes the use of a mat-drawer to display a custom component. The challenge arises when the custom component gets nested inside a div (with class="mat-drawer-inner-container") automatically adde ...

How can I simulate or manipulate the element's scrollHeight and clientHeight in testing scenarios?

In my JavaScript code, I have a function that checks if an HTML paragraph element, 'el', is a certain size by comparing its scrollHeight and clientHeight properties: function isOverflow(element: string): boolean { const el = document.getEleme ...

Updating a specific field in a Firestore document: A step-by-step guide

Is there a way to retrieve and edit a particular field in Angular Firestore? https://i.sstatic.net/fiElK.png ...

Defining optional parameters in TypeScript

Currently, I am working on implementing strong typing for a flux framework (specifically Vuex). Here is my current code: const actions = { first(context: Context, payload: string) { return doSomething(context, payload); }, second(context: Context) { r ...

Replacing `any` in TypeScript when combining interfaces

Currently using Express and attempting to explicitly define res.locals. Issue arises as in the @types/express package, Express.Response.locals is declared as any, preventing me from successfully overwriting it: types/express/index.d.ts: declare namespace ...

Customizing the Material UI v5 theme with Typescript is impossible

I'm attempting to customize the color scheme of my theme, but I am encountering issues with accessing the colors from the palette using theme.palette. Here is a snippet of my theme section: import { createTheme } from "@mui/material/styles&qu ...

Angular 5 Error Messages for HTTP Interceptors

I'm facing an issue regarding Angular 5: HTTP Interceptors. I am still new to this, so please bear with me as I grasp the concepts. Here is the error message that I encountered: compiler.js:19514 Uncaught Error: Provider parse errors: Cannot instan ...

What is the proper way to specify the interface as Dispatch<Action>?

My goal is to create an interface with the dispatch function without using Redux. interface DispatchProps { dispatch: (action: { type: string }) => void; } export function addTwoToNumber({ dispatch }: DispatchProps) { dispatch({ type: '@addTwo ...

Is it possible to implement a redirect in Angular's Resolve Navigation Guard when an error is encountered from a resolved promise?

I have integrated Angularfire into my Angular project and am utilizing the authentication feature. Everything is functioning properly, however, my Resolve Navigation Guard is preventing the activation of the component in case of an error during the resolve ...

Angular is reporting that the check-in component is nonexistent

I encountered an error in my Angular 8 application while working on a component. The error seems to be related to nested components within the main component. It appears that if the component is empty, the error will be shown, but if it's not null, th ...

Creating a React prop type validation that is dependent on the value of another prop

I am in the process of creating a custom React Table component, with the following TableProps structure: export interface ColumnType<ItemType, Key extends keyof ItemType = keyof ItemType> { header: string; key?: keyof ItemType; renderCell: (val ...

incapable of altering the function of individual parts within ionic 3

I am currently working on creating a list of people for users to connect with. When a user clicks on the connect button, it should send a connection request to the chosen person. However, I am facing an issue where clicking on the connect button changes th ...