How can I use AngularJS resource to fetch data from a URL that requires both query parameters and post data?

Requirement: To send data to an endpoint using a post of data, include the startdate and endate in the querystring of the url. Here's an example:

The data payload should only contain the locationIDs and Criteria as shown below.

The Resource Definition

I attempted to move the startDate and endate out of the query object as well.

ByLocationResource: $resource(
    ByLocationEndpoint,
    null,
    {
        query: {
            startDate: '@startDate',
            endDate: '@endDate',
            locationIds: ['@locationIds'],
            Criteria: '@Criteria',
            method: 'POST'
        }
    }
),

The EndPoint Definition

var ByLocationEndpoint = https:/servername/byLocation/?startDate=:startDate&endDate=:endDate');

How can I consolidate the querystring in the URL endpoint with the post data?

The Service:

    function ByLocation(startDate, endDate, Criteria, locationIds) {
        _ByLocationResource.query(
            {

                startDate:startDate,
                endDate:endDate,
                locationIds: [locationIds],
                Criteria: Criteria


            });


    }

I experimented with this variation:

function ByLocation(startDate, endDate, Criteria, locationIds) {
        _ByLocationResource(startDate,EndDate).query(
            {

                locationIds: [locationIds],
                Criteria: Criteria


            });


    }

Do I have to resort to using $http instead of an endpoint and resource?

The browser shows a 400 bad request that looks like this:

Request URL:

Evidently, the startDate and endDate parameters are not being populated.

Answer №1

A guide to effectively utilizing AngularJS Endpoints with QueryString and Post data

Here is the recommended template structure:

ByLocationResource: $resource(

    ByLocationEndpoint,
    {
        startDate: '@startDate',
        endDate: '@endDate'
    },
    {
        query: {

            Criteria: '@Criteria',
            locationIds: '@locationIds',
            method: 'POST',
            isArray: true
        }
    }
),

When making a call, the first two parameters fill in the query string for the endpoint, while the second set of parameters provide the Post data. The method here is named 'query', as we are querying data based on the POST parameters, with results constrained by the provided start and end dates.

MyService.ByLocation(
    {
        startDate: startDateTime,
        endDate: endDateTime
    },
    {
        Criteria: {

            Id: Id,
            Minutes: Minutes,
            Id2: Id2
        },
        locationIds: [5, 6, 7, 8]
    }
);

The code within the MyService service that calls the query method.

function ByLocation(dates, payload) {

    return ByLocationResource.query(dates, payload).$promise;
}

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

Effortless glide while dragging sliders with JavaScript

In the code below, an Object is looped through to display the object key in HTML as a sliding bar. jQuery(function($) { $('#threshold').change(updateThreshold); function updateThreshold () { var thresholdIndex = parseInt($(&apos ...

Transforming each element of an observable array by updating their properties with data retrieved from an ajax request using knockout

In my ViewModel "AppViewModel", I am fetching JSON data to create the model. One of the properties, "totalSessions", requires an ajax call to be fetched. While my code runs without errors, the view does not update as expected. var jsonapparray = []; ...

After the checkbox is clicked, I must send a boolean value to the function through the input flag in AngularJS

<input class="bx--toggle" id="toggle-view" type="checkbox" ng-model="vm.monthView" ng-change="vm.getRelevantData()" ng-attr-data-modal-target="{{vm.alertForSaveAll ? '#add-save-all-alert-modal': 'undefined'}}"> Within this p ...

Caution: It is important for each child to be assigned a distinct key - How to pass an array in

While following ReactJS tutorials on Scrimba, I came across a scenario where id props need to be passed in an array. import React from 'react'; import Joke from './components/Joke.js' import jokesData from './components/jokesDat ...

Navigate back to the parent directory in Node.js using the method fs.readFileSync

I'm restructuring the folder layout for my discord.js bot. To add more organization, I created a "src" folder to hold all js files. However, I'm facing an issue when trying to use readFileSync on a json file that is outside the src folder. Let&ap ...

When iterating through a table, an error occurs stating that the property "rows" is not available on type HTMLElement (

Issue Error TS2339 - Property 'rows' does not exist on type HTMLElement when looping through table in Angular 7 Encountering error when trying to loop through HTML table in Angular 7 Currently working with Angular 7 and facing an error while ...

What are the steps to ensure a successful deeplink integration on iOS with Ionic?

Recently, I was working on a hybrid mobile app for Android/iOS using Nuxt 3, TypeScript, and Ionic. The main purpose of the app is to serve as an online store. One important feature involves redirecting users to the epay Halyk website during the payment pr ...

When the 'Show More' button is clicked, one Div will smoothly slide over another Div

I've been struggling for hours to find a way to make one DIV slide over another DIV below it instead of pushing it down. The setup is quite straightforward. I have a script that reveals more text when the 'Show More' button is clicked. Desp ...

Attaching a click event to an element located within the template of a directive

I decided to create a reusable directive in order to make a common component, but I am facing an issue trying to capture the click event of an element inside the template used within the directive. Take a look at the code snippet below for better understa ...

What is the best way to extract all ID, Name values, and locations from my JSON object and store them in an

I am working with a JSON object named 'tabledata' array. Let's say I want to iterate through all the objects inside it and extract the ID values, so the output would be 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. I also need to access other key-value pai ...

The function for the Protractor promise is not defined

UPDATE: After some troubleshooting, I believe I have identified the issue causing it not to work. It seems that I am unable to pass arguments along when calling flow.execute(getSpendermeldung). Does anyone have a better solution than wrapping the ApiCall i ...

Safari having trouble auto-playing Vimeo iframe embed

Update 6/26/23: Seems like a mysterious change occurred, as now the Vimeo video on project pages is playing automatically for me in Safari without any specific reason. It's working fine on Chrome too. Not sure if Vimeo made an update or if it's r ...

The task "grunt-karma.js" is currently being loaded, but unfortunately an error has occurred: SyntaxError - An unexpected identifier was found

Encountering an issue when loading "grunt-karma.js" tasks while all other tasks are loading correctly. This problem started to occur after updating several dependencies, including grunt-karma and karma. Here is the section from my package.json: "grunt-ka ...

How can you implement WriteFile in a GET Request without causing the response to be blocked

During the initialization of the app, I require a specific request to be made. This request entails parsing a portion of the JSON response into JavaScript and then saving it to a file. Simultaneously, the rest of the response needs to be sent to the front ...

Lazy loading AngularJS UI router named views is an efficient way to improve performance

AngularJS UI router named views loading based on user access rather than loading at the time of state route access. Example: $stateProvider .state("login", { url: "/login", templateUrl: getTemplateUrl("login/Index") }) ...

Update the reference of the 'this' keyword after importing the file

I am currently utilizing react-table to showcase the data. My intention is to house my table columns outside of the react component due to its size and for reusability purposes. I created a table configuration file to contain all of my table configurations ...

Using regular expressions to replace strings in JavaScript

I have a URL that resembles the following http://localhost:12472/auctions/auction-12/lots/sort/something/12 I am looking to switch it out with this new URL http://localhost:12472/auctions/auction-12/lots/sort/somethingelse/12 Here, somethingelse can be ...

Prioritizing the execution order of useEffect in Next.js

Here is the code snippet from my _app.tsx useEffect(() => { console.log(1) }, []); And this portion of code is from my index.tsx useEffect(() => { console.log(2) }, []); Currently, in the console it prints 21 However, I want it to print 12 ...

A user-friendly JavaScript framework focused on manipulating the DOM using a module approach and aiming to mirror the ease of use found in jQuery

This is simply a training exercise. I have created a script for solving this using the resource (function(window) { function smp(selector) { return new smpObj(selector); } function smpObj(selector) { this.length = 0; i ...

Best practices for handling loops in Angular's $http service to ensure smooth rollback functionality

Seeking guidance on best practices for Angular $http POST requests. Currently, I am gathering an array of data to later post to my Spring Data REST database. To achieve this, I need to iterate through the $http POST request in order to allow all the data ...