The downfall of a promise leading to another promise

There are two REST calls:

The first one is:

http://localhost:8080/sample/rest/ser/out/2

Which returns:

{"num":"2"}

The second REST call is:

http://localhost:8080/sample/rest/ser/person/list2/two

Which returns:

[{"personName":"Rahul Shivsharan","personId":123},{"personName":"Mehul Sarnikar","personId":34},{"personName":"Praful Patel","personId":343}]

In order to invoke the second REST call based on the response of the first one, I have implemented an AngularJS code as follows:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <meta charset="ISO-8859-1">
    <title>Insert title here</title>
    <script type="text/javaScript" src="../scripts/angular.js"></script>
    <script src="../scripts/angular-resource.js"></script>
    <script type="text/javascript">
        var myApp = angular.module("myApp",['ngResource']);
        myApp.factory("CountService",function($resource){
            return $resource("../rest/ser/out/:num",{
                num : "@num"
            });             
        }).factory("PersonService",function($resource,CountService,$interval){
            var obj = new Object();

            obj.getPersonList = function(inputTxt){

                return CountService.get({
                    "num" : inputTxt
                }).$promise.then(function(response){
                    var url = "../rest/ser/person/list2/";
                    if(response.num === 2){
                        url += "two";
                    }else if(response.num === 3){
                        url += "three";
                    }else{
                        url +=  "other";
                    }
                    return $resource(url,{});
                });
            };
            return obj;


        }).controller("myCtrl",function($scope,PersonService){
            $scope.getInfo = function(){
                PersonService.getPersonList($scope.inputTxt).query().$promise.then(function(response){
                    $scope.personList = response;
                });
            }
        });
    </script>
</head>
<body ng-controller="myCtrl">
    <h1>{{num}}</h1>
    <br />
    <input type="text" ng-model="inputTxt" /><br/><br/>
    <input type="button" value="ENTER" ng-click="getInfo()" />
    <br /><br /><br />
    <table border="2">
        <tr ng-repeat="per in personList">
            <td>{{per.personName}}</td>
            <td>{{per.personId}}</td>
        </tr>
    </table>
</body>

The functionality of this code is based on user input for the first REST call, followed by the execution of the second REST call after the success of the first. The response from the first call is converted to match the URL parameters of the second call.

However, there seems to be an error:

Error Message:

TypeError: PersonService.getPersonList(...).query is not a function
at Scope.$scope.getInfo (index.html:65)
at Parser.functionCall (angular.js:10795)
at angular.js:19036
at Scope.$get.Scope.$eval (angular.js:12632)
at Scope.$get.Scope.$apply (angular.js:12730)
at HTMLInputElement.<anonymous> (angular.js:19035)
at angular.js:2843
at forEach (angular.js:325)
at HTMLInputElement.eventHandler (angular.js:2842)

I thought that a promise should return another promise which should work properly, but it doesn't. Can you suggest a better solution and point out where I might have gone wrong?

Answer №1

As pointed out by @AlexMA, you are retrieving a $resource "class" object.

To solve this issue, consider adding an additional .then statement before calling .query():

$scope.getInfo = function(){
    PersonService.getPersonList($scope.inputTxt)
        .then(function(resource) {
            return resource.query().$promise;
        })
        .then(function(response){
            $scope.personList = response;
        })
    ;
};

You can see this approach in action here: http://plnkr.co/edit/P00rbUk1ld8eo0VD6OyN?p=preview

Answer №2

The issue lies in the fact that the method PersonService.getPersonList does not include a property named query which is expected to be a function. It is unclear what exactly is returned by getPersonList, but even if it returns a promise, it will still fail since promises do not contain a query function in 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

Is it possible that the images are unable to load on the page

The frontend code successfully retrieves the image links sent by the backend but encounters issues displaying them. Despite confirming that the imgUrl data is successfully fetched without any hotlink protection problems, the images are still not appearing ...

How can I resolve a 404 error in JavaScript when trying to run a PHP script using XMLHTTPRequest and the file path is not found?

Every time I click the button on the user interface to trigger the Javascript communication with PHP in order to display a "Hello world" page, I keep receiving a "{"timestamp":"2021-06-10T20:14:59.671+00:00","status":404,"error":"Not Found","message":"","p ...

Tips for implementing dynamic typing with Prisma

Encountering the error "this expression is not callable" while using the findUnique method with dynamic models. How can this type error be resolved? export const isFound = async ( model: Prisma.ModelName, id: string | number, idName: string ): Promis ...

Altering the JavaScript variable by selecting an option from a dropdown list

After downloading a choropleth map from leafletjs.com, I encountered an issue with multiple JS files labeled by year (e.g. us-states2012.js, us-states2013.js). The challenge now is to implement a drop down menu in such a way that selecting a specific year ...

React State not refreshing

Currently tackling a challenging e-commerce project and facing an obstacle with the following component: import React, { useEffect, useState } from 'react'; const Cart = () => { let [carts, setCarts] = useState([]); let [price, se ...

Error Encountered During Building Apache Cordova Project in Visual Studio 2015

Encountering an issue when attempting to launch my cordova project on both an android device and android emulators. Currently utilizing visual studio 2015 In dire need of assistance! Error can be viewed in the image below: ...

Comparing Knockout's foreach with Angular's ng-repeat

My Experience with Knockout and Transition to Angular. In my current project, I am dealing with a table where data is dynamically added through a scroll event. Whenever the user scrolls down, 20 new rows are appended to the end of the table. The total row ...

Bringing in two JavaScript files with identical names

Recently, I encountered a challenging situation. I am working with material-ui and nextjs, both of which have a module called Link that is essential for my project. import { Link } from '@material-ui/core'; However, this setup is causing compil ...

Insert multiple text box values as a new entry in an SQL database

Currently, I am implementing a code snippet to incorporate additional text boxes within a form. The main purpose is to enable users to input multiple languages they are proficient in. <script> jQuery(function($) { var i = 0; ...

Challenges with Expanse in Object-Oriented JavaScript

I'm currently working on incorporating objects from a JSON file into an array within my JavaScript object using the $.getJSON() function in jQuery. However, I've encountered scope challenges where the array elements appear to be defined inside th ...

Showing a collection of articles on a webpage using Nuxt/content - Step by step guide

I have implemented the nuxt/content module to establish a documentation website. In a recent post on the Nuxt blog, they demonstrated displaying content in a separate index.vue page and post details on the _slug.vue page. My goal is to present a list of ...

Locate the textbox that pertains to the element currently in focus

My HTML is structured as follows: <tr> <td colspan="2" class="borderBottomCell"> <div class="benefitInfo" style="WIDTH: 99%! important;"> <asp:DropDownList ...

What are the steps to execute Mike Bostock's D3 demonstrations?

I've been attempting to run Mike Bostock's See-Through Globe demonstration, but I encountered issues with the correct referencing of his json files when attempting to replicate it locally. The problem stems from this particular line of code: d3. ...

Utilize JQuery to easily share content with line breaks on WhatsApp

In order to properly share the content of a web page on WhatsApp using jQuery, I encountered an issue with text containing line breaks within the divblock3 element. <div class='divblock3'><p><p>Lorem Ipsum is simply dummy .<b ...

Rails partial successfully loads after AJAX request has been made

After making an ajax call, I am rendering a partial: Show.js.erb $("#notice_feed").html("<%=j render 'shared/notice_feed' %>") _notice_feed.html.erb <ol class="notices" id="notice_list"> <%= render @notices %> </ol> ...

Is there a way to prevent redirection to the homepage after submitting a login form?

Having trouble with my Single Page application: every time I refresh the page after rendering the login form, it goes back to the homepage. How can I prevent this and make sure the page stays on the login form even after a refresh? This is what my homepag ...

Error Alert: Express configuration encounters Unforeseen character <

This is how I have set up my Express: const express = require('express'); const app = express(); app.use(express.static('public')); app.get('*', function (req, res) { res.sendfile('dist/index.html'); }); app.li ...

Comparing jQuery's min-width and width properties: A guide on eliminating pixels

Exploring some basic jQuery and JavaScript here. When I use the .width() method, I get an integer value. However, when I use .css('min-width'), it returns a value in pixels which makes it challenging to perform calculations. What would be the be ...

Is there an alternative solution to the issue of the jQuery resize() event not triggering when an input is

Despite the fact that the jQuery event resize() should trigger when the width of an input box changes, it seems to be malfunctioning. As per the jQuery API documentation, the resize event is supposed to go to the (window) handler. So my query here is, what ...

How to insert a span element within a link tag in Next.js/React.js

Looking to create a breadcrumb using microdata in a Next.js and React.js project. Initially, I tried the following: <li itemProp="itemListElement" itemScope itemType="https://schema.org/ListItem"> <Link href={'/index&a ...