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

Content update failed due to an error

Why is an error occurring when attempting to update the content? The edited value is retrieved in the componentDidMount function without any issues. Posting the content works fine, but updating it using reactjs and django tastypie api throws an error as fo ...

Creating a Three-Dimensional Bounding Box in THREE.js

After successfully utilizing the OBB.js in three.js examples to fetch the center, halfSize, and rotation values, the next step is to determine how to calculate the 8 corners of the bounding box based on this information. Additionally, we need to understa ...

Utilizing ReactJS to make an Ajax request

I am trying to transfer data to individuals and then display it using the array map function. export default class App extends Component { constructor(props) { super(props); this.state = { persons: [], }; } componentDidMount() { $ ...

The postman does not retain any data

I am currently facing an issue where I am using Postman to enter a post into a MongoDB server, but the post returns empty. Even after checking my server, nothing has been entered and there are no errors displayed. Here is the route file: router.post(&apos ...

Troubleshooting: AngularJS fails to refresh UI when using SignalR

When I attempt to incorporate this angularjs code into a signalR function, the UI does not update. Even using $scope.$apply() does not trigger a digest. This is the code snippet: var notificationHub = $.connection.progressNotificationHub; notificationHub. ...

How can I send an API request with a callback function as an argument using node.js?

If you want to access the getPlayers(callback) method, it is described as follows: getPlayers(callback) callback - This parameter is necessary. It will be called with an object of players players - An object that contains all the players who are curr ...

After updating from angular4 to angular 5, the npm test is failing with the error message "TypeScript compilation cannot find test.ts file"

After upgrading my app from Angular4 to Angular 5 using the steps provided on https://update.angular.io/, I encountered an issue. While I can successfully run ng-serve and ng build without any problems, the npm test command for ng test is failing with the ...

Forwarding images from a server to a client using socket.io and node.js

I am encountering an issue where I am trying to receive an image via socket.io in node.js and then forward it to a client (browser). However, the image sent through the message to the browser is not being recognized or displayed. Interestingly, if I save ...

AngularJS - utilizing the directive $parsing to evaluate an expression and bind it to the scope object

I have set up my isolated directive to receive a string using the @ scope configuration. My goal is to convert this string into an object on the scope, so that I can manipulate its properties and values. Here's how it looks in HTML: <div directiv ...

Creating a text field in an input box using JavaScript or jQuery to input data

At work, I need to use a web application that requires me to fill in two input fields. However, when I try to do so using JavaScript commands, the strings appear but the "Add" button remains disabled. Additionally, even if I enable the button, the data can ...

The UI-SELECT feature in angular-js does not seem to be displaying

I've added the necessary ui-select js and css files to my page : <link href="assets/plugins/ui-select/select.min.css" rel="stylesheet" type="text/css" <script src="assets/plugins/ui-select/select.min.js" tyle="text/javascript" </script> ...

Angular QR code scanner: Simplifying the process of scanning

Can anyone provide guidance on incorporating a Live QR Scanner into an Angular application? I attempted to use the Zxing library but struggling to find detailed documentation for integration with Angular. Your assistance is greatly appreciated. Thank you ...

When using jQuery AJAX, the script is returning blank values

Facing a frustrating issue here. I'm sending an AJAX request to a PHP file, but when I check Chrome Network Tools, it doesn't return any JSON data. However, when I try posting the same data using POSTMAN in Chrome, it returns correctly. Also, if ...

What is the purpose of being able to include additional scripts within package.json files?

I am attempting to include a new script in the package.json file under the scripts section. For instance, I have the following: { "scripts": { "delete": "rm -f wwwroot/*.js wwwroot/*.css wwwroot/*.html wwwroot/*.map" "watch": "npm run delete; parc ...

Delivering information to personalized components using React Bootstrap

I am working with a custom styled checkbox that is part of a mapped data array. {nfcArray && nfcArray.map((item, key) => { return ( <tr class="hover"> <td className="cell_style pl-3 pl-lg-5"> ...

In strict mode, duplicate data properties are not allowed in object literals when using grunt-connect-proxy

I recently started following a tutorial on AngularJS titled "Hands on Angularjs" by Tutsplus. In the tutorial, the instructor uses the grunt-connect-proxy package to redirect ajax requests to a Rails server running on localhost:3000. However, I believe the ...

Automatically populate the article number field once the article name has been entered

I am currently working on a HTML <form> using PHP. Within this form, there are three <input> fields. The goal is to have the second <input> field automatically populate once the first one is filled out. This will involve triggering an HTT ...

Tips for embedding an object into an iframe source

I have successfully integrated a YouTube iframe into my HTML file. However, I would like the source URL to be dynamically generated based on data from the backend rather than manually inputting the URL as shown below. In the admin panel, there is an object ...

Embarking on a New Project with Cutting-Edge Technologies: Angular, Node.js/Express, Webpack, and Types

Recently, I've been following tutorials by Maximilian on Udemy for guidance. However, I have encountered a roadblock while trying to set up a new project from scratch involving a Node/Express and Angular 4 application. The issue seems to stem from the ...

Bypass ajax request with the use of a returned promise

I've come across a scenario where I have a function within a class that is designed to return a promise for deleting an item. Here's what the function looks like: function Delete(){ // if(this.id == ""){ // return ?; // } ...