Utilizing Global Variables and Passing Values in Ionic 3

It seems like my issue is rather straightforward, but there is definitely something eluding me.

After logging in, I need to store a TOKEN for HTTP requests in a global variable. Upon successful login, the HTTP get method returns an object with the HTTP code (200, 403, 403), a message ("Success"), and the TOKEN. I then pass this object to the HOME.ts page through NavController.

this.navCtrl.setRoot(HomePage,{
    data   <<--- Object                        
  });

However, when I attempt to assign this "data" to an object of type "Login"

export class Login {

code:number;
token:string;
message:string;

constructor(code?:number, token?:string, message?:string){
    this.code = code;
    this.token = token;
    this.message = message;

}

}

Inserting the attribute Login.token into the global variable results in nothing happening.

I conducted some tests and this is my current understanding.

In the HOME.ts file, I included console logs to investigate further.

 console.log(this.navParams.data.data); ----> RESULT 1

console.log(this.navParams.get("data"));    ----> RESULT 2

this.dadosRest = this.navParams.get("data");

console.log(this.dadosRest);  ----> RESULT 3

console.log(this.dadosRest.token); -----> RESULT 4

RESULTS 1, 2 and 3:

{success: {…}}

success : code : 200 message : "Welcome admin - This is your token (generated by a previous call)" token : "676f71bab54dad7589c3d1b6b5f5b24de0f8c484" proto : Object proto : Object

RESULT 3 :

undefined

Why am I unable to incorporate this returned data into the Login object for processing?

Answer №1

Avoid using global variables at all costs. Instead, consider utilizing a shared service where you can create a service that is injected into the components. You can then use a method to store your token and another one to retrieve the stored value. Alternatively, you can store it in a storage solution like Ionic Storage, or opt for a more complex approach such as using a state container like Redux.

In any case, refrain from cluttering the global scope. While you might be tempted to do something like

window.token = 'the token'

this is not recommended practice.

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

When I click a button in d3 to refresh the data on my bar graph, the text fails to update accordingly

I've successfully created a series of data lists that modify the bargraph. Unfortunately, due to their differing x and y values, they end up printing new values on top of existing ones. Shown below is an image illustrating the issue where x and y val ...

Challenge with dynamic parent routes

In my React application, different routes are loaded through various parent URLs. For example: {["/sat/", "/act/", "/gre/", "/gmat/", "/toefl/"].map((path) => ( <Route key={path} path={path ...

Using Firebase with Angular 4 to fetch data from the database and show it in the browser

Currently diving into Angular 4 and utilizing Firebase database, but feeling a bit lost on how to showcase objects on my application's browser. I'm looking to extract user data and present it beautifully for the end-user. import { Component, OnI ...

The property '.....' is missing an initializer and has not been explicitly assigned in the constructor

I want to address an issue with a similar question title that was asked 5 years ago on Stack Overflow. The problem is related to declaring a variable as an array of a specific object type in an Angular component using TypeScript 4.9. Even though I tried t ...

Text aligned at the center of the Y and X axis

I am looking to center my content along the Y axis instead of only on the X axis. To prevent the page from expanding beyond its current size, I have applied the following CSS: html { overflow-y: hidden; overflow-x: hidden } What I want to achieve is havi ...

Why is the getElement().getProperty("value") function not functioning properly?

I am facing an issue with reading a property in my web component. I am puzzled as to why it is not working correctly. I created a simple example, and after clicking the button, I expect to retrieve the value of the property, but it returns null. I am unsur ...

Using jQuery each, the output is an undefined Object or HTMLElement

Using jQuery's each/getJSON to iterate through a data.json file, collect and format the data, and display it on the page within the #output div. The functionality is working correctly, except for the unexpected addition of [object HTMLElement] that a ...

In JavaScript, escape is comparable to android decode

I used a JavaScript method to encode a string: var result = escape('Вася') The resultant string is: "%u0412%u0430%u0441%u044F" Now I need to decode this string in Java. How can I achieve this? The following attempt did not work: URLDecod ...

What is the process to set up a WebSocket on Tornado for a production server rather than on a local machine?

Recently, I've delved into the world of WebSockets but have only experimented with them in a localhost environment while developing locally. Following this informative tutorial on real-time data visualization: https://medium.com/@benjaminmbrown/real-t ...

Ways to enable a user to edit a calculated property in VueJS?

I am currently working on collecting data that the user can download, and I am facing a challenge in determining the best way to handle the filename. To ensure the default filename is dynamic and based on the current date, I believe creating a computed pro ...

What is the best way to display the values from an array in a child component and pass them to the

How can I retrieve values from an array in the child component and display that data in the parent component? Initially, I was only displaying data from the array when the 'save' button was clicked. Now, I need to display the array by default. ...

Angular 2: Harnessing the power of Observables with multiple Events or Event Handlers

In the component template, I have grouped multiple Inputs and their events like this: <tr (input)="onSearchObjectChange($event)"> <th><input [(ngModel)]="searchObject.prop1"></th> <th><input [(ngModel)]="searchObje ...

Leveraging subcomponents within a main component in Angular 2

I've structured my Angular2 application with 3 levels of nested components: layout, header, and search. Below is the directory structure: layout/ ├── header/ │ ├── search/ │ │ ├── search.component.ts │ │ ...

Communicate crucial event prevention details using the event object in Angular

Here is an innovative approach I've discovered for passing information about whether to prevent an event: var info = { prevention: false }; $scope.$emit("nodeadd.nodeselector", info); if (!info.prevention) { $scope.addNodeCb(type, subtype); } ...

Having trouble with a beginner problem that's hindering the functionality of my code

I have been struggling with a particular piece of code and it is driving me crazy as I am unable to locate the source of my error: $.post($form.attr('action'), $form.serialize(), function (result) { console.log(result); if (result.succes ...

What is the most effective method for accurately tallying the number of matches in a Datalist using the Input value as a reference

I have set up a datalist element with an associated input element for autocompletion in modern browsers: HTML code <input type="search" id="search" list="autocomplete" /> <datalist id="autocomplete"> <option value="c++" /> < ...

Experiencing trouble with calculating the total value of an array of objects due to NaN errors

I've been working on developing this web application in VUE.js, but I'm facing an issue with a specific function where I am attempting to sum the values of each object within an array. This is resulting in a NaN (Not a Number) error. Let's t ...

What is the best way to overlook content-encoding?

I am in need of downloading a file from a device. Sometimes, the file might have an incorrect content-encoding, specifically being encoded as "gzip" when it is not actually compressed in any way. When the file is properly gzipped, retrieving the content u ...

Executing the onSuccess callback in Ajax without any ability to manipulate the ajax requests

My dilemma lies in needing to execute a JavaScript function upon the successful completion of an AJAX call. Unfortunately, I am unable to directly manage the AJAX calls as they are handled by the DNN5 framework. Is there a way for me to trigger my functio ...

Adding ngChange programmatically in Angular without using attributes is a common challenge faced

I am attempting to replicate the functionality of the ng-change attribute within a directive without making changes to the HTML (thus excluding the use of the ng-change property). After examining the Angular source code for the ngChange directive, I have ...