Difficulty retrieving information using AngularJS service post selection of item

Currently, I am working on a project involving an AngularJS application. While using the service testPanelService, I encountered a problem where selecting an item from a list correctly logs the details of the selected item. However, when attempting to fetch related information using the service panelInvestigationService, the expected data is not received.

The following is part of the service file:


// Interfaces and classes defined here...

Below is a snippet from my TypeScript controller relevant to this issue:


// Controller code provided here...

Here is the corresponding HTML:


// HTML template included here...

Upon selecting an item, the console outputs the following response from testPanelService: Selected item: {code: '02', name: 'Pregnancy', retired: false, ...} However, when making a call to panelInvestigationService.query(testPanelId), I expect to receive an array of investigation details as demonstrated below:


// Expected output structure shown here...

Despite this, I do not see the anticipated result in the console after executing panelInvestigationService.query(). The selection log works properly, but the subsequent data retrieval does not function as intended.

Some attempts I have made include:

  • Ensuring that testPanelId is correctly passed to panelInvestigationService.query().
  • Inspecting the network request through the browser's developer tools, which confirms the correct testPanelId being used for the request.
  • Adding console logs to validate the response structure from panelInvestigationService.query().

I am uncertain why panelInvestigationService.query() is failing to return the expected data. Is there a possibility that there is an issue with how I am managing the promise or updating the dataSet? Any insights or recommendations on this matter would be highly valued.

Answer №1

After identifying the issue within the service, I made adjustments to ensure it functions properly:


export interface ITestPanelInvestigationService
  extends IAggregateRootService<ILaboratoryTest, string> {
  queryByInvestigationSetId(
    investigationSetId?: string, //this corresponds to the itestpanel code
    page?: IPageRequest
  ): ng.IPromise<IPageReponse<ILaboratoryTest>>;
}

interface ITestPanelInvestigationResource
  extends IResourceService<ILaboratoryTest> {
  fetch: ng.resource.IResourceMethod<IPageReponse<ILaboratoryTest>>;
  queryByInvestigationSetId: ng.resource.IResourceMethod<IPageReponse<ILaboratoryTest>>;
}

export class TestPanelInvestigationService
  extends EntityService<ILaboratoryTest, string, ITestPanelInvestigationResource>
  implements ITestPanelInvestigationService
{
  static $inject = ['TestPanelInvestigationResource'];
  constructor(private resource: ITestPanelInvestigationResource) {
    super(resource);
  }
//Renamed the query method for clarity
  queryByInvestigationSetId(investigationSetId?: string, page?: IPageRequest): ng.IPromise<IPageReponse<ILaboratoryTest>> {
    // Set default page request if not provided
    if (angular.isUndefined(page)) {
      page = { page: 0, size: 32000 };
    }
    return this.getResource().queryByInvestigationSetId({
      investigationSetId: investigationSetId,
      page: page.page,
      size: page.size,
      sort: page.sort,
    }).$promise.catch(error => {
      console.error('Error querying investigation set ID:', error);
      throw error; // Log error or handle appropriately
    });
  };
//Applied the code logic here
  ITestPanel = (code: string): ng.IPromise<any> => {
    return this.getResource().fetch({ id: code})
      .$promise;
  };
}

export class TestPanelInvestigationResourceService {
  private apiRoot: string = Settings.serverResource('api/get-individual-investigations-by-set/');
  constructor(private $http) {}
  
//Implemented the respective method with correct syntax for 'ID'
  queryByInvestigationSetId = (investigationSetId: string) => {
    this.$http.get(
      Settings.serverResource(`api/get-individual-investigations-by-set/${investigationSetId}`)
    );
  };
  fetch = (id: string) => this.$http.get(`${this.apiRoot}${id}`);

  get = (id: string) =>
    this.$http.get(`${this.apiRoot}${id}`).success(function (data) {
      if (data) {
        data = angular.fromJson(data);
      }
      return data;
    });

  update = (id: string) => this.$http.put(`${this.apiRoot}${id}`);
}

TestPanelInvestigationResource.$inject = ['$resource'];

export function TestPanelInvestigationResource(
  $resource: ng.resource.IResourceService
): ITestPanelInvestigationResource {
  const resourceUrl = Settings.serverResource(
    'api/get-all-test-panels/:investigationSetId'
  );

  return <ITestPanelInvestigationResource>$resource(
    resourceUrl,
    {},
    {
      query: { method: 'GET', isArray: false },
      fetch: { method: 'GET', isArray: false },
      queryByInvestigationSetId: {
        method:'GET',
        url: Settings.serverResource('api/get-all-test-panels/:investigationSetId',),
        isArray: false,
      },
      get: {
        method: 'GET',
        transformResponse: function (data) {
          if (data) {
            data = angular.fromJson(data);
          }
          return data;
        },
      },
      update: { method: 'PUT' },
    }
  );
}

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

What is causing the lack of data binding between AngularJS and my array?

Here is a sample I created: http://jsfiddle.net/grL95/9/ angular.module('myApp', []) .controller('Ctrl', function($scope) { $scope.name = 'Hello'; $scope.myNumbers = [10, 20, 30]; $scope.printNumbers = function() ...

Designing a query feature to explore a Sequel Database utilizing a 'RETRIEVE' approach

In my index.erb, I've created a search bar with the following code: <nav> <div class="nav-wrapper"> <form> <div class="input-field"> <input id="search" type="search" placeholder="Search..." required> ...

Guide to connecting to various controllers in Angular

To streamline the process of fetching data from the server and paginating it for all resources, I developed a custom ListCtrl. However, before setting it up, this controller needs to receive certain configurations such as the path to the resource and defau ...

What is the process for adding new data to a data source without overwriting existing information?

I need assistance with a react native app I am developing. I am currently facing an issue where the data received from a fetch request needs to be displayed in a list view. However, each time new data is fetched, it overwrites the previously received data ...

Issue encountered in Babel version 6 with the transform-es2015-classes plugin in loose mode, causing a SyntaxError when using async/await

After updating to the latest version of Babel v6, I encountered an issue with the transform-es2015-classes plugin in loose mode (https://github.com/bkonkle/babel-preset-es2015-loose/blob/master/index.js#L8) causing problems with async/await functions. Here ...

Changing the link color within a repeater in ASP .NET when it is clicked

The given code snippet is being executed on an iPhone 4, causing some CSS elements like Hover to not function as expected. <asp:Repeater ID="rpt" runat="server"> <HeaderTemplate> <div class="table withshadow"> </Header ...

What is the best way to limit angular-xeditable to accept only positive numbers?

This is my code snippet. I'm looking for an attribute that will only allow positive numbers to be entered. <td><span e-step="0.001" editable-number="myNumber" onaftersave="updateValue()">{{ myNumber }} </span></td> ...

Header Overflow Error Encountered in Node.js GET Request

While attempting to programmatically submit a form through Google forms using a GET request, I encountered the error message Parse Error: Header overflow. The debug code output is as follows: REQUEST { uri: 'https://docs.google.com/forms/d/e/9dSLQ ...

The initial click event for the input element in Jquery is not functioning correctly

I found a jQuery date selector online and the script looked something like this... <script type="text/javascript> $(document).ready(function () { $("#date3").click(function() { $("#date3").scroller({ preset: 'datetime' }); wheels = []; whe ...

Equivalent of $evalAsync in KnockoutJS

I am looking for a way to execute a function only once in a custom binding handler in order to resize some divs based on their contents. While I can easily achieve this in angularjs using $evalAsync, I am trying to find a similar solution for knockout. ht ...

Prevent unauthorized entry to css and javascript files

Is there a way to prevent direct access to a file? I want the file to be used on my website, but I want to block it from being accessed directly. For example, if you try to open this link: https://example.com/style.css, you will see an error message. Howev ...

Learn how to automatically access keys in local storage using Angular

I need to implement a way to store data in local storage so that it persists even when the page is refreshed. In my HTML file, there is a button that triggers a function in my TypeScript file. This function takes a parameter 'game', which is an i ...

The attempt to save data failed with a timed out error for Operation `todos.insertOne()` after 10000ms of buffering

const express=require("express"); const { stringify } = require("querystring"); const router= express.Router() const Db=require("../models/Db") router.get("/",(req,res)=>{ res.render("index.hbs"); }) .post("/addData",async(req,res)=>{ const ...

Ways to prevent adding duplicate elements to a state array in React.js?

The state provided below is within my class component. I need to prevent adding duplicate objects to an array in my state as shown below: this.state = { frequency: { time: [ {time:"20:15",timezone:"IST"}, ...

Examining for a TypeError with Typescript and Jasmine

In my current project, I am faced with the challenge of writing unit tests in Typescript for an existing library that was originally written in plain JS. Most of our page logic is also written in plain JS. Some functions in this library throw exceptions if ...

Persisting Undefined Values Even After Proper Prop Passing

I'm currently working on fetching and passing coaching data as props to another component for rendering on the frontend. I need to pass these props to the CoachingCard Component in order to display the coaching values. However, I'm encountering ...

Exploring the capabilities of combining Typescript with withStyles in the latest @material-ui/core framework

I have been working on updating some old Typescript code that was using material-ui@next to now use @material-ui/core. Typescript Version: 2.8.3 @material-ui/core: 1.1.0 I created a simple component that accepts a single prop, but when I try to use it, t ...

Vue textarea not accepting null values

My current setup includes the following dependencies: - "vue": "3.2.26", - "vee-validate": "4.5.6", - "typescript": "4.5.4" While working on a textarea field in vue3, I encountered an issue Here's a snippet with vee-validate integration import { Fie ...

Troubleshooting Vue 3: Dealing with Synchronization Issues Between Keyboard Input and

I am currently working on a Vue 3 autocomplete component and I've come across a strange issue that I can't quite figure out. The component emits two events: "update:search" to update the search variable in the parent component, and "change" whic ...

real-time visual data updates using ng2-charts animation

I am currently working on a real-time data dashboard using Angular 2 and ng2-charts. The main issue I am facing is that whenever the data associated with the chart changes, all the data points on the chart are redrawn. Since the data will be updating every ...