AngularJS is capable of dynamically altering the URL based on the specific HTTP method being used, such as

I have implemented Angular factories to connect ajax requests with my web api. Below is an example of how the factory is structured.

app.factory('QuestionContainer', ['$resource', function ($resource) {
return $resource('http://localhost:52133/api/questioncontainerapi/:id', null,
    {
        'update': { method: 'PUT' },
        'publish': { method: 'Put', url: 'http://localhost:52133/api/questioncontainerapi/:id/Publish/' }
    });
}]);

You can observe that I have inserted :id between two actions in the URL and the current method specified is Put. When using the factory in the controller as follows ->

QuestionContainer.publish({ id: 1 });

the request URL becomes

http://localhost:52133/api/questioncontainerapi/Publish/
with a body of { id: 1 }. If I switch to the Get method, the request URL changes to
http://localhost:52133/api/questioncontainerapi/1/Publish/
, which is the desired URL.

How do I configure Angular to achieve this behavior? Appreciate any guidance!

Answer №1

If you're encountering an issue, make sure to include the param in your code snippet:

app.factory('CustomContainer', ['$resource', function ($resource) {
return $resource('http://localhost:52133/api/customcontainerapi/:id', {id: '@id'},
    {
        'update': { method: 'PUT' },
        'submit': { method: 'POST', url: 'http://localhost:52133/api/customcontainerapi/:id/Submit/' }
    });
}]);

Check out this jsfiddle for reference.

You can monitor the requests made in the console.

Tutorial

url: /example/:param

It's crucial to define the param by using {param: 'value'}. This ensures that the URL will always be resolved to /example/value.

If you want dynamic URLs based on variables, use:{param: '@var'} Here, var is a variable associated with either the instance resource or the data object passed to a class resource.

CustomContainer.submit({ id: 1 }); // Data object: {id: 1}

To access /example/3, follow these steps:

CustomContainer.submit({ var: 3 }); // Class
var custom = new CustomContainer({var: 3}); // Alternatively: new CustomContainer(); custom.var = 3;
custom.$submit();

For further details, refer to the official documentation: $resource

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

Can an asynchronous function potentially return an object with a "then" function included?

When using the JavaScript async function (or a regular function that returns a Promise), any object with a function containing a "then" field is considered a Promise. However, is it possible to have such an object be the resolved value of a Promise? For e ...

Switch between classes based on the query using the Ajax response

In order to retrieve data from a database and determine if the field "is_recurring" is set to 1 or 0, I am utilizing an ajax call to my functions.php file. This value is based on a selection made in a dropdown menu. Depending on the result returned by the ...

Real-time data updates using AJAX in Ruby on Rails

Currently, I am working with Rails and jquery to implement dynamic content using ajax. However, one issue I am facing is extracting the current user ID from the URL For instance, if the URL is www.mywebsite.com/users/20 In my javascript file, I require ...

-g option must be enabled for jscoverage to function properly

To install jscoverage globally, use the following command: npm install jscoverage -g Do you know what purpose the -g option serves? Without using the -g option, my system does not recognize jscoverage as a valid command. ...

Sending multiple AJAX post requests in succession

I'm encountering an issue with my AJAX POST request for a login form. Every time I submit the form, regardless of whether the combination is correct or incorrect, it sends multiple requests Incorrect login: function incorrect() { $('#loginM ...

Leveraging recompose utility within the structure

I am exploring the use of recompose utility functions as a React element, enabling me to incorporate them into JSX as higher-order components (HOC). const enhancedInput = props => { return (<OnlyUpdateForKeys keys={['name']> ...

The event handler is malfunctioning in Django's inline formset

I have created an inline formset with the following structure: class EventForm(ModelForm): class Meta: model = Event exclude = ['created'] class GalleryForm(ModelForm): class Meta: model= Gallery exclude ...

Following the parsing of the list of months, the sequence undergoes a

After receiving the JSON encoded object from the server side in PHP MONTHLY_FORMAT, I am reading that object in jQuery as: var MONTHLY_FORMAT = '<?php echo $MONTHLY_FORMAT; ?>'; When checking the console output, it looks like this: {"0 ...

Webstorm seems to be having trouble identifying Next.js

When I create a Next.js app using the command npx create-next-app my-app --use-npm Everything is successfully installed, but when using WebStorm, I noticed that it does not auto import the <Link> component from Next.js. I have to manually import it ...

Issue encountered while integrating Angular with Grails

Below is the content of my index.gsp file <!DOCTYPE html> <html ng-app="myApp"> <head> <title>my app</title> </head> <body> <input type="text" data-ng-model="test"/> {{test}} </body> <script src ...

Navigating objects in an Array in React

const [formData, setFormData] = useState( { "student": [ { name:"", age: "" } ] } ); How can I update the state object inside an array and pass ...

Attempting to store an array of JSON objects in the state, and then utilizing the `map` method to render

I'm just starting out with React. Currently, I'm attempting to store an array of JSON objects in the state and then map those items into the component render. I'm feeling a bit lost on how to debug this as there are no console errors showi ...

How to Build Node 0.4.7 on Ubuntu 11.10?

Having trouble compiling 0.4.7 for Heroku support as I am unable to enable ssl support required by express. I've tried installing libssl-dev and even attempted manual installation of openssl, but no luck so far. Any suggestions on how to get node up a ...

AngularJS remove a row from a table disrupts the formatting

Hello! I am attempting to delete rows from a table in Angular. I want the first two rows to have a red background and the rest to have a white background. If I try to delete the last row, it gets deleted but the color remains for the first row only (it sh ...

What are the steps to remove text within a list item using jQuery or regular JavaScript in a WordPress theme?

I need to remove the word "previous" from an li element in a wordpress theme. the text to delete <ul class="flex-direction-nav"> <li class="flex-nav-prev"> <a class="flex-prev" href="#">Previous ...

Tips for associating an id with PrimeNg menu command

Within my table, I have a list of items that I would like to enhance using PrimeNg Menu for dropdown menu options. The goal is to enable navigation to other pages based on the selected item id. When a user clicks on a menu item, I want to bind the id of th ...

Different color for background of division

I am working with a structure that looks like this: <div class="wrapper"...> <a href="#"...>blah</a> <div class="post"...>stuff</div> </div> This structure repeats multiple times on a dynamic page. I am looking f ...

Install global npm modules in alternative directories for Node.js

Currently, I am encountering difficulties with installing global modules on my Ubuntu Unix OS. Upon investigating the location of the node_modules folder, I discovered that npm had installed some global modules in /usr/lib/node_modules while others were ...

Error encountered while trying to import: 'getMovies' function is not available for export from 'C:/Users/hp/vidly/src/fakeGenreService'

I am in the process of developing a simple React app. In the same folder, I have a file named 'fakeMovieService.js' that I imported into movies.jsx. The fakeMovieService.js file contains a function called getMovies() which retrieves all movie val ...

Improving List performance with React.cloneElement

I am uncertain about the usage of React.cloneElement within a List component. Is it recommended to avoid using it, especially when dealing with a large number of elements in the list? Does React.cloneElement cause unnecessary re-renders that can be optimal ...