Using $http call to pass attributes to controller in Web Api 2 using attribute routing

I am currently working on an $http call in my project:

$http({
        method: 'GET',
        url: '/api/PhotoSubmit/GetCategories',
        accept: 'application/json'
    })
        .success(function (result) {
            $scope.categories = result;
        });

... that requires sending a parameter to this HTTPGET method :

[Route("api/PhotoSubmit/GetCategories/{id}")]
    [HttpGet]
    public object GetCategories(int id)
    {
        return FileServices.GetCategoriesForUser().Select(c => new { Id = c.Id, Name = c.Name });
    }

The routing is set up correctly but I'm unsure of how to access it using Angular/JavaScript to send data to the controller (OR... how the route-call should be formatted in the $http call)

The URL for reference is:

http://localhost:63203/Index.html#/photosubmit/1

Answer №1

For my web api endpoint, I'm utilizing $resource within a factory instead of $http.


Within services.js, the setup looks like this:

var app = angular.module('app.service', ['ngResource']);

app.factory('api', ['$resource', function ($resource) {
'use strict';
return {
    Categories: $resource('/api/PhotoSubmit/GetCategories/:id', {id: '@id'})
    };
}]);

When calling it in the controller, I use:

$scope.categories = api.Categories.get({id:"1"});

If you're interested in dynamically handling data once it's returned, you can wait for results using $promise.

api.Categories.get({id:"1"}) .$promise .then(function (results){ $scope.categories = results; });


Update: To pass a variable to $routeParams, here's how I achieved it:

Inside app.config, the following was added to set up an id parameter:

$routeProvider
    ...
    .when('photosubmit/:id', {
        templateUrl: "photo.html",
        controller: "PhotoController"
    })
    .otherwise({ redirectTo: '/' });

In the controller, get the param using

$scope.$routeParams = $routeParams;

Ensuring this is placed at the beginning to prevent it from being lost or undefined.

Now, access the route-defined variable with $scope.$routeParams.id

Answer №2

The identifier can be transmitted via the URL itself.

url: '/api/PhotoSubmit/GetCategories/1',

Alternatively, you can also include it in the parameters.

$http({
    url: '/api/PhotoSubmit/GetCategories', 
    method: "GET",
    params: {id: 1}
 });

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 streaming AWS Lambda response in nodeJS

I have a serverless AWS Lambda function that I need to trigger from my Node.js application and stream the response back to the client. Despite searching through the official documentation, I cannot find a straightforward way to achieve this. I am hoping to ...

Accessing a property's value from a different property within a Class' initialization function

I encountered a challenge while trying to access the value returned in one method within a property of another method belonging to a different constructor. The specific error message I received was "TypeError: Cannot read property 'name' of undef ...

How can I close the menu when a menu item is clicked in a React.js application?

I am facing an issue where I want to close the menu when clicking on any menu item in React JS. The functionality works fine with a button icon but not with individual menu items. How can I resolve this problem? I have been trying to implement it using CSS ...

Using jQuery, identify when a key has been pressed within a three.js environment

How can I detect a keypress within a designated scene contained in a div with the id "world"? I've written the following code in an attempt to achieve this, but it doesn't seem to be working properly. Here is the code snippet: $('world&apos ...

Temporarily withhold the execution of useEffect until useSelector successfully fetches data from the Redux store within a React

I have a functional React component called Tasks_1. Initially, I retrieve the userId from the Redux store, which is working successfully. After obtaining the userId from the Redux store, I want to use it in a useEffect hook to fetch data from the backend. ...

AngularJS and the Angular UI Router were combined for the first time in

Hey everyone, I could really use some help as I'm just diving into the world of AngularJS. Can anyone guide me on how to tackle these pesky errors? Error: app.js:6 > Uncaught ReferenceError: angular is not defined Error: angular.min.js:6 > Unc ...

Utilize the power of RxJS to send numerous post requests within an Angular application

I have a form where users input names and count numbers. My goal is to append the number to each name. For example, If a user enters "worker" and a count of 5, I want to add numbers from 1 to 5: worker-1, worker-2, worker-3, worker-4, worker-5. After cr ...

Ordering BufferGeometries in Three.js for Accurate Rendering

After consulting the discussion on the previous inquiry, I have been working on constructing models in BufferGeometry and have come to understand that the transparent flag plays a role in the rendering order: objects with transparent materials will be rend ...

Ajax request unable to load Image Slider

I'm currently implementing an Image Slider from this source For the site structure, I've set up an index.html file to display all the pages, allowing navigation by changing the content within <div id="isi">. Here's a snippet of the in ...

The iPad scroll did not meet the condition for reaching the bottom

Looking to modify the footer when the bottom of the page is reached via scrolling, I implemented the following code: if($(window).scrollTop() + $(window).height() == $(document).height()) This condition successfully detects whether the scroll has reached ...

Assign a value of null to SynchronizationContext rather than utilizing ConfigureAwait(false)

Within my library, there are both synchronous and asynchronous versions of a method available. However, both versions ultimately call an asynchronous method internally. Unfortunately, I have no control over this asynchronous method as it utilizes async/awa ...

Angular Bootstrap-Select: Displaying options even after selection

There seems to be a bug in the angular bootstrap select demo section. After selecting an option, the dropdown continues to display options instead of hiding them. This issue does not occur when the ng-model attribute is omitted. You can view an EXAMPLE he ...

The functionality of the JQuery $.post method may be compatible with Firefox but may encounter issues when

I've encountered an issue with my website where certain functions that update the database using $.post work perfectly in Firefox, but fail to function properly in Internet Explorer. I'm struggling to identify the root cause of this problem. Here ...

Ways to customize the hover effect for react-bootstrap navbar link

I'm looking to update the hover effect color from white to green, but I'm having trouble finding the correct CSS code for it. <Navbar fixed='top' collapseOnSelect expand="md" variant="dark" className="animate ...

Dynamic Positioning in Javascript Application

When working on a javascript project, I needed to create a div element. Here is the code snippet I used: const divStyle = {left: offsetPercent + '%', 'position': 'absolute'}; <div style={divStyle}/> However, I encounte ...

Mysterious data organization - transform into an object

As I interact with an API, there is a value that I cannot quite pinpoint. My goal is to transform this string into a JavaScript object, but the process seems complex and confusing. Does anyone have insight on what this data represents and how it can be co ...

What is the proper way to utilize a function in C# that integrates with a window form using TypeScript?

I am currently working on a code that is in c# and utilizes a web browser. My goal is to convert the existing JavaScript code to Angular 7 and Typescript. Below is the c# code and the corresponding JavaScript code used to access the c# function from JavaS ...

Displaying values dynamically as they transition between states in Reactjs

There are four components that I'm working with - UserHome, SearchFlight, Events, and Alerts. The UserHome component is where I import all the other components: <SearchFlight/> <Events /> <Alerts /> Within the SearchFlight compone ...

Facing some unexpected issues with integrating Django and AngularJS, unclear on the cause

In my simple Angular application, I encountered an issue. When I run the HTML file on its own in the browser, the variable name "nothing" is displayed as expected. However, once I integrate the app into Django by creating a dummy view that simply calls a t ...

In Vue.js, the 'select' option is consistently set as the default choice

Encountering an unusual issue with a select field in vue.js. Desired outcome: a select field with no default option selected. In regular html, this is easily achievable. Here is the jsfiddle Link: https://jsfiddle.net/odsf3awr/ <select id="test" s ...