Navigating from the login page to the dashboard in AngularJS, passing along JSON information

Currently, I am working on developing a basic application using Angular JS. Within this project, I have two HTML files named Login.html and Dashboard.html. When I launch the Login.html file, everything operates smoothly. Upon successful login, my goal is to display the user dashboard with JSON data retrieved from the server at the time of login.

Below is an excerpt of my code (main.js):

  var app = angular.module('NovaSchedular', []);
  app.factory('MyService', function() 
  {
    var savedData = {}
    function set(data) 
    {    
        savedData = data;      
     }
    function get() 
    { 
        return savedData;
    }

    return {
      set: set,
      get: get
    }

});



function LoginController($scope,$http,MyService,$location) 
{

    $scope.login = function(str) {
        console.log(".......... login called......");
        var validEmail=validateEmail(email.value);
        
        if(validEmail && password.value != ""){
            $http.post('./nova/TaskManager/public/user/login?email='+email.value+'&password='+password.value).success(function(data, status)
            {                      
                console.log(data);
                var result=data.response;
                console.log(result); 

                if (result=="success")
                {
                    $scope.userId=data.user_id;
                    $scope.email=data.email;
                    $scope.Name=data.name;
                    $scope.password=data.password;
                    $scope.Type=data.type;

                    console.log("........"+$scope.userId);
                    console.log("........"+$scope.email);   
                    console.log("........"+$scope.Name);   
                    console.log("........"+$scope.password);   
                    console.log("........"+$scope.Type); 

                    MyService.set(data); 
                    console.log(data);

                    alert(data.message); 

                    window.location.href='./Dashboard.html';  
                    //$location.path('./Dashboard.html', data);   

                }
                else
                    alert(data.message);
            });
        }             
     }

}



function DashboardController($scope,$http,MyService) 
{

   $scope.userInfo = MyService.get();    

}

Upon successfully logging in, I can see that the server response (JSON data) is being received under the LoginController. However, my next challenge is to have this data readily available on the Dashboard page so that it can populate the dashboard with the respective user information.

I attempted achieving this by:

   window.location.href='./Dashboard.html'; 
   //$location.path('./Dashboard.html', data);

However, I encountered an issue where the data was not being passed from the LoginController to the DashboardController despite redirecting to Dashboard.html successfully. Consequently, upon inspecting the console for Dashboard.html, an empty JSON object is displayed.

It's puzzling why the data isn't being transferred. Any insights or suggestions would be highly appreciated.

Answer №1

Check out this example of controller code:

app.controller('LoginController' function($scope,$http,MyService,$location) 
{

$scope.login = function(credential) {
    console.log(".......... login called......");
    var validEmail=validateEmail(credential.email);
    if(validEmail && credential.password!= ""){
      MyService.login(credential);
    }
  }
});

Also, take a look at this snippet:

app.controller('DashboardController',function($scope,$http,MyService) 
{

   $scope.userInfo = MyService.getDashboardData();    

});

In the file named MyService.js:

var app = angular.module('NovaSchedular', []);
app.factory('MyService', function() 
{
    var dashboardData;
    var obj={
        login:function(credential){
            $http.post('./nova/TaskManager/public/user/login?email='+credential.email+'&password='+credential.password).success(function(data, status, headers) {
                dashboardData=data;
                window.location.href='./Dashboard.html';
            })
            .error(function(data, status, headers, config) {
                console.error('error in loading');
            });
          },
        getDashboardData:function(){
            return dashboardData;
        }
    }

    return {
        login:obj.login,
        getDashboardData:obj.getDashboardData
    }

});

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

Tips for positioning elements in a way that prevents CSS fixed from overlapping upon page loading

Is there a way to adjust my navigation menu to prevent overlap upon page load, but have it overlap when scrolling down (Dynamic nav bar)? Check out my current setup: Upon initial page load, the navigation bar overlaps the text. I would like the navigatio ...

The serialization of a ManyToMany through field

I am experiencing difficulties when it comes to serializing my items/orders along with their quantities. The current results I am obtaining are as follows: { "id": 1, "_current_status": null, "orderitem_set": [ { "item_id": 2, "quanti ...

Interacting between two PHP scripts using Ajax

I'm having trouble with an AJAX request between 2 PHP scripts. One script returns data in the form of a JSON string: [{'foo':'bar'}] The other script makes a simple HTTP request to it: $c = new http\Client; $r = new http&bs ...

Modify the ColVis Appearance in Datatable Using JavaScript

Where can I modify the background color for the 'Hide/Show columns' label in the ColVis.js file? ...

The deletion request using the form in Express is experiencing issues and not functioning properly

When attempting to delete data from a database using a form in node.js and express, I am encountering issues with the deletion process. It seems that there are only two methods available - get and post - and no specific delete method. router.js code rout ...

Identify line counts and hyphenated lines in a text box with the help of regular expressions

I have been struggling to find a solution to the problem of excluding lines starting with double hyphens when using regular expressions. I need to count single lines separately and double hyphenated lines separately, and display them outside the text area. ...

Is the response of the post not being received?

here is an example of HTML code: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="js/input.js"></script> </head> <body> <form> <ta ...

Icons positioned absolutely outside of components will not be responsive to user interactions

How can I ensure that the icon on my tab bar can be clicked only when it covers a specific part of the screen, and not when it is in other areas? Any suggestions on how to fix this? Image Below is the code for the tab bar: <View style={{ background ...

import the AJAX response into a table format

With over 10000 rows in Data-table 1.10, I am looking to populate the table body using ajax response. Currently, I am returning the data as an array and iterating over it on the frontend in HTML. This results in the data-table rendering all the rows regard ...

What is the best way to assign the value of a random array element to my state variable?

Currently, I am attempting to choose items randomly from my 'items' array. How can I assign the randomly selected item as the value of the 'randomItem' state? Here is my progress so far. var items = ['joe', 'joe', &a ...

Tips for eliminating the "Your connection is not secure" page in Firefox when using "Selenium with JavaScript"

My current project involves automating a secure URL using Selenium, WebdriverIO, and JavaScript. However, the page keeps redirecting to a "Your connection is not secure" message. I have attempted to address this issue by setting various preferences in the ...

Utilizing Dropwizard for hosting static HTML files

I'm in the process of developing an application using dropwizard and angularjs. I have configured my AssetsBundle as follows: bootstrap.addBundle(new AssetsBundle("/assets", "/", "index.html")); The challenge I am facing is that I want multiple page ...

How can a browser reload a document when navigating back to the previous page?

I am facing an issue with the browser's built-in go back function. Imagine I have two pages: Page1 and Page2. Page1 downloads a .json file and displays its contents on the webpage. On Page2, users can add new data to the .json file. However, if a ...

Accessing data from arrays containing objects through an AJAX Request

I am trying to work on an ajax request, but I'm struggling with it. Here is the current ajax call I have: $.ajax({ type: 'GET', url: 'https://teamtreehouse.com/garrettsanderson.json', dataType: 'json', success: f ...

Looking for assistance with converting a basic script into a Joomla 2.5 module and resolving issues with Java integration

I'm having issues with my code in Joomla 2.5. It seems like the Java function is not functioning properly within Joomla. Can someone assist me with troubleshooting this problem? mod_mw_pop_social_traffic.php <?php defined( '_JEXEC' ) or ...

Activating CORS for .ajax POST requests

I am encountering an error with my .ajax request that reads as follows: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.com/api/GetData. This issue can be resolved by either moving the resource to ...

Developing JSON output in Grails

I'm currently developing a Grails web application to transform the provided input data into the desired output format, which will then be utilized to display a fancyTree view. I have implemented a controller class with the code snippet below. However, ...

Understanding the connection between PHP and JSON

Looking for recommendations on where to find a solid introduction to JSON in connection with PHP. Any advice is appreciated! ...

Tips for efficiently generating a two-dimensional numpy array using JSON objects

I am working with nested JSON data that has the following structure: [{'game':'001', 'animals': [{'name':'Dog', 'colour':'Red'}, {'name':'Horse', 'age':&apo ...

Failed to transfer form data to server using ajax in Node.js

I am attempting to utilize AJAX to send form data to a Node.js server. I had previously inquired about this on the following post. Below is a glimpse of my code: <div id="inputid" style="width: 400px; height:400px"> <p> Kindly input value ...