Exploring ways to display response data on a different page using AngularJS

With this code snippet, I am authenticating email and password using the customerlogin() method. The method returns JSON data that I need to display on the next page. Essentially, I want to pass the data obtained from customerlogin() to then() and then forward it to /customerprofile. Any assistance would be greatly appreciated.

logUserIn(form) {
    this.submitted = true;

    if (form.$valid) {
      this.Auth.customerlogin({
          email: this.operator.email,
          password: this.operator.password
        })
        .then(() => {

          // Successfully logged in, redirect to customer profile
          this.$location.path('/customerprofile');
        })
        .catch(err => {
          this.errors.login = err.message;
        });
    }
  }

//Additional file Auth.js

customerlogin({
      email,
      password
    }, callback) {
      console.log('Customer Authentication Method');
      return $http.post(properties.customer_login, {
        email, password
      })
        .then(res => {
         properties.GetId = res.data.id;
          $cookies.put('token', res.data.token);
          currentUser = User.get();
          return currentUser.$promise;
        })
        .then(user => {
          safeCb(callback)(null, user);
          return user;
        })
        .catch(err => {
          Auth.logout();
          safeCb(callback)(err.data);
          return $q.reject(err.data);
        });
    }

I need to display the data in these textboxes: take a look at the image here

Answer №1

Your login function should call a service method that handles the ajax request and saves the response as an object property within the service. The controller can access this data because the service has been injected, eliminating the need to pass any parameters. Angular will automatically watch for changes in the object.

Here's an example:

angular.module('someModule')

.service('someService', function($http) {
    return {
        loginCall: function(...) {
            // make ajax call here
            return loginStuff; // must be an object (or wrapped in one)
        };
    };
})

.controller('SomeController', ['someService', function(someService) {
    var sc = this; // using controllerAs syntax

    sc.login = function(form) {
        someService.customerlogin(...).then(...).catch(...);

        // since someService is injected, its properties are available on the controller's scope
        // you can use it in your view like {{someService.loginCall.dataProperty}}
        ...
    };
}]);

Note: You may need to add module injections, but this should give you a good starting point.

Answer №2

Initially, attempt using the following format for your .then method:

  .then(function (data) {
      $log.debug(data); //output passed data to console through angular
  });

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 TypeError with Next.js and Firebase: Unable to access properties of undefined (specifically 'apps')

My goal is to create an authentication system using NextJS and Firebase. The issue I am facing is in my firebaseClient.js file, where I am encountering the error "TypeError: Cannot read properties of undefined (reading 'apps')". Here is a snipp ...

Updating an image using AJAX and Flask

I have a situation in HTML where I need to constantly update an image file with the latest images that come in. Below is the Flask code snippet: @app.route('/uploads/update_file', methods=['GET', 'POST']) def update_file(): ...

"Encountered a 400 Error while trying to access the OpenAI

var openairequest = new XMLHttpRequest(); const payload = ({ "model": "text-davinci-003", "prompt": "say this is a test" }); console.log(payload) openairequest.open("POST",`https://api.openai.com/v ...

Challenges encountered in d3.js when parsing through data sets

For the past two days, I have been struggling to solve this error and I'm at a loss. Every time I try to add data to the visualization, I encounter the following error: Uncaught TypeError: Cannot read property 'length' of undefined It seem ...

What is the best way to retrieve the first items from an array of objects?

When I send an axios request like this: async fetch() { await this.$axios.get(`my_api_url`) .then(response => { this.data = response.data; }).catch(() => { console.log('error') }) }, The response contains the following d ...

Varied approaches to managing responsive layouts

I am encountering an issue with the responsive design of a website I am currently developing. Scenario: The website features 3 different layouts for Desktop, Tablet, and mobile devices. These layouts consist of similar components with slight CSS adjustmen ...

There is no specific Type identified that aligns with the Controller non-MVC in ASP.net Web API

I am currently in the process of developing a web application using a non-MVC web API in .NET. AngularJS is being utilized to make calls to the API. Let's take a look at the Router: public static class WebApiConfig { public static void Register( ...

What steps do I need to take to incorporate dialog-polyfill into my React application?

Incorporating Firebase and FirebaseUI in my React application for phone number registration has been successful on Google Chrome desktop. However, when testing it on different browsers, such as through , I encountered an issue with the country code selecto ...

How can I effectively transfer parameters to the onSuccess callback function?

In my react-admin project, I'm utilizing an Edit component and I wish to trigger a function upon successful completion. <Edit onSuccess= {onSuccess } {...props}> // properties </Edit> Here's the TypeScript code for the onSuccess fun ...

It is possible that an infinite loop has occurred, as the program has now exceeded

In my project block on this sandbox, I have utilized tools like cherrio, https://cors-anywhere.herokuapp.com/, axios along with custom functions to navigate through pagination, extract data using web scraping techniques, and store the extracted data in an ...

Tips on leveraging JQuery's $.when for handling ajax requests sequentially

How can I effectively use $.when in JQuery with chained promises to ensure my ajax requests are processed in the correct order? I have a dynamic array called costArray containing various objects. For each item in this array, I initiate an Ajax request nam ...

A more intelligent approach for generating JSON responses using Mysql

Here is the code I have on my server side using Node.js: var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'SOMEUSER', password: 'SOMEPASSWD', database: 'SOMED ...

tips for accessing the useState value once it has been initialized

When using the state hook in my code, I have: const [features, setFeatures] = useState([]) const [medicalProblem, setMedicalProblem] = useState([]) The medicalProblem variable will be initially populated with a response from an API call: useEf ...

Is Node.js going to continue to provide support for its previous versions of node modules?

I currently have a website that relies on the following dependencies. While everything is working smoothly at the moment, I can't help but wonder about the future support of these packages by node.js. I've looked into the legacy documentation of ...

JQuery .click Event doesn't center elements even with transform-origin adjustment

In the JSfiddle provided below, you can see that after a click event occurs, two span (block) elements rotate 45deg to form an "X". However, both elements are slightly shifted left, creating an off-center "X" relative to the parent's true center-origi ...

What is the best way to use jQuery to insert this block of HTML into a page from a JSON response?

<script type="text/javascript"> var dataString2 = 'run=captchagood&comment=' + comment; $.ajax({ type: "POST", url: "process.php", data: dataString2, dataType: "json", error: 'error', success: function ...

Implementing dynamic element creation and class implementation using JavaScript

Having issues with dynamically creating an element in JavaScript using innerHTML. Here's the code snippet: var newElement = document.createElement("tr"); newElement.innerHTML = ['<td><a href="javascript:void(0);">Test Suite</a> ...

What are some strategies for breaking down large components in React?

Picture yourself working on a complex component, with multiple methods to handle a specific task. As you continue developing this component, you may consider refactoring it by breaking it down into smaller parts, resembling molecules composed of atoms (it ...

Organize routes into distinct modules in Angular 6

Currently grappling with routing in my Angular 6 application. Wondering if the structure I have in mind is feasible. Here's what it looks like: The App module contains the main routing with a parent route defining the layout: const routes: Routes = ...

The issue with the angular-ui ui-calendar is that it does not reflect changes made to the Event Source Object or

I implemented fullcalendar.js into my angular app using angular-ui / ui-calendar. (angularjs 1.3.10, fullcalendar 2.2.6, ui-calendar 0.9.0-beta.1, jQuery 2.1.3, moment 2.9.0 & angular-moment 0.9.0) Within the calendar, I utilize the dayClick functio ...