Exploring AngularJS: Retrieving data based on a specific ID from a JSON document

Within my controller class, I extract the ID of a specific user from the URL and pass it on to the OrderService. My goal now is to fetch the data associated with this ID from a JSON file. How can I accomplish this task?

OrderCtrl

'use strict';
angular.module('Orders').controller('OrderCtrl', ['$scope', '$state', "SettingService", "OrderService","$stateParams", function($scope, $state, SettingService, OrderService,$stateParams) {


 var OrderId = $stateParams.orderId;

 $scope.orders = [];

  OrderService.getOrderDetails(OrderId).then(function(response){
    $scope.orders = response.data.data;
  }, function(error){

  })

}]);

OrderService.js

angular.module('Orders')
    .service('OrderService', ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService",
     function($http, $state, $resource, $q, SettingService, $localStorage, MessageService) {
        var service = {
            getOrderDetails : function(OrderId){
            Here I desire to fetch data from a JSON file

    });
            }

        }

        return service;
    }]);

Answer №1

Consider implementing something similar to the following:

'use strict';
angular.module('Orders').controller('OrderCtrl', ['$scope', '$state', "SettingService", "OrderService", "$stateParams", function ($scope, $state, SettingService, OrderService, $stateParams) {

    var OrderId = $stateParams.orderId;
    $scope.orders = [];

    OrderService.getOrderDetails(OrderId).then(function (response) {
        $scope.orders = response.data.data;
    });

}]);

// This serves as a repository for the remote json collection.
angular.module('Orders').service("OrderService", ['$http', '$state', '$resource', '$q', 'SettingService', '$localStorage', "MessageService",
        function ($http, $state, $resource, $q, SettingService, $localStorage, MessageService, handleResponse) {
            // Providing public API.
            return ({
                getOrderDetails: getOrderDetails
            });
            // Retrieve all items from the remote collection.
            function getOrderDetails(OrderId) {
                var request = $http({
                    method: "get",
                    url: '/ajax/order/details', // example
                    params: {'id': OrderId}
                });
                return (request.then(handleResponse.success, handleResponse.error));
            }
        }]);

angular.module('Orders').service('handleResponse', function ($http, $q, $location) {
    return {
        error: function (response) {
            // The server's response should be in a standardized format. If not,
            // attempt to normalize the response on our end.
            if (!angular.isObject(response.data) || !response.data.message) {
                // Handle unknown error and attempt to reload.
                return ($q.reject("An unknown error occurred."));
            }
            // Return expected error message.
            return ($q.reject(response.data.message));
        },
        success: function (response) {
            return (response.data);
        }
    };
});

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 incorporating a return statement within a network request function that is already returning information pertaining to the request

Is there a way to retrieve the data extracted from within newReq.on('response', (response) => {? var request = require('request'); const cheerio = require('cheerio'); const { app, net, BrowserWindow } = require('elect ...

Node Express application experiences issues with Handlebars rendering additional empty objects from JSON arrays

Currently, I am attempting to retrieve data from a REST API call and display it as a list using Handlebars, which functions as my view engine in a Node Express App. Below is the route I am using: router.get('api/projects', function(req, res){ ...

Accept a JSON-sending POST request in a JSP file via JavaScript

I have developed an HTML page with an input field. Using javascript, I extract the input value, convert it into JSON format, and attempt to send it through ajax. Additionally, I have a JSP application where a Java method processes this JSON data to store i ...

Tips for broadcasting a router event

Currently, I am working with 2 modules - one being the sidenav module where I can select menus and the other is the content module which contains a router-outlet. I am looking for the best way to display components in the content module based on menu selec ...

Adjust the initial letter of every word with JQ Capitalization

I am currently working with a large JSON file using JQ to filter out unnecessary elements. While I have successfully achieved this, I encountered an issue with certain values being all capitalized strings. Unfortunately, JQ does not provide a built-in func ...

What are the steps to make a basic slider with jQuery without using plugins?

<script> const animateImages = function(){ $("#slider").animate({"left":"-=1775px"},10000,function(){ $("#slider").animate({"left":"0px"},10000); animateImages(); }); }; animateImages(); </script> I incor ...

Using jQuery to create a seamless scrolling experience to both the top of a page and to

I've been looking for solutions on how to add both jQuery scroll to top and scroll to anchors, but haven't found any integrated options. Is it possible to achieve this here? We currently have a jQuery function in place to add a scroll-to-top fea ...

Using restKit for handling specific JSON responses that do not directly correspond to the core data managed objects

Let's consider the scenario where we are working with an API that provides data in JSON format and we aim to utilize Restkit for mapping to two core data objects: "products" and "resources". These two objects have a many-to-one relationship, meaning o ...

What is causing Puppeteer to not wait?

It's my understanding that in the code await Promise.all(...), the sequence of events should be: First console.log is printed 9-second delay occurs Last console.log is printed How can I adjust the timing of the 3rd print statement to be displayed af ...

Tips for accessing key-value arrays in PHP sent via Ajax POST requestsHow to effectively retrieve key-value pairs

Is there a way to access a key and value array passed through an ajax call to a PHP function on the PHP side using the $_POST method? var eImages = [{ ProductID: ProductID, Image: image1Name, ImagePath: image1Path }, { ProductID: Produc ...

Sending various values via a click in an HTML link

Hello, I am attempting to pass multiple values using the HTML onclick function. I am utilizing Javascript to generate a table dynamically. var user = element.UserName; var valuationId = element.ValuationId; $('#ValuationAssignedTable').append(&a ...

RxJS Observables trigger the onCompleted function after completing a series of asynchronous actions

I have been attempting to design an observable that generates values from various asynchronous actions, particularly HTTP requests from a Jenkins server, which will notify a subscriber once all the actions are finished. However, it seems like there might b ...

Implement a click event using jQuery specifically for Internet Explorer version 7

How can I add an onclick attribute using jQuery that is compatible with IE7? So far, the following code works in browsers other than IE8 and Mozilla: idLink = Removelst(); var newClick = new Function(idLink); $(test1).attr('onclick', null).clic ...

The Bootstrap carousel spiraled into disarray

I am facing an issue with the basic bootstrap carousel. My goal is to make the slides move every four seconds. The current setup of the carousel code is as follows: $(document).ready(function() { fixCarousel(); }); function fixCarousel() { $('.c ...

Issues with Unity JSON API

I am currently facing a challenge as I attempt to save an n x m field array as JSON in a text file within Unity. Due to the limitation of Unity not supporting array types for top-level JSON deserialization, I have created a custom class structure like this ...

Updating a form field dynamically with AJAX in Laravel

I'm working on updating the field $medic->current based on certain logic that I have in mind. I'm quite new to using AJAX and would appreciate a little guidance to kick things off. In my code, I am calculating the difference between two dates ...

Parameter within onClick function that includes a dot

I'm attempting to design a table that enables an onClick function for the Change Password column's items so my system administrator can adjust everyone's password. Each onClick triggers the "ChangePassOpen" function which opens a modal with ...

Having trouble identifying the data variable. Uncaught ReferenceError: edu_id has not been defined

How can I successfully pass the edu_id from an AJAX request to my Laravel controller? Utilizing anchor tags <a href="javascript:void(0);" onclick="showEditEducation(some_specific_id);" title=""><i class="la la-pencil"></i></a> Im ...

Preventing circular dependencies while upholding the structure of modules in Express

I am developing an express app in ES6 and organizing my files by functionality. In this structure, each module has an index.js file that is responsible for exporting relevant methods, classes, etc. Other modules simply require the index.js from another mod ...

Combining the value of $(this) to create an identifier name

I am attempting to create a hover effect on an h1 element that triggers the glowing effect on a span element with an id that corresponds to the value of the h1. While I have successfully set up a glowing effect for a sentence, I am struggling to replicate ...