Using AngularJS $resource to implement complex service calls

Yesterday, I began my journey with angularjs and found myself at this particular section of the tutorial that demonstrates the usage of $resource to access data from services. In my ASP.Net MVC setup, I encountered a slight hiccup due to the difference in configuration of where the json files are stored. The json file containing the phone list and the detailed description files for each phone are located in separate directories. The issue seems to stem from this line of code:

return $resource('phones/:phoneId.json', {}, {
      query: {method:'GET', params:{phoneId:'phones'}, isArray:true}

Based on my directory structure, I had to make modifications to the line above in order to access the json file containing the phone list.

  return $resource('/MyAngularScripts/:phoneId.json.htm', {}, {
      query: { method: 'GET', params: { phoneId: 'jsonPhonedata' }, isArray: true }

The reason for changing the extension to .htm was to avoid adding another handler to IIS express. Despite successfully viewing the phone list, I encountered an issue when attempting to access the detailed description of each phone from a separate directory. The directory in question is:

/Content/PhoneData/{all the various phone data json files here}

When trying to view the detail file located at

/Content/PhoneData/motorola-xoom-with-wi-fi.json.htm
by hitting the url
/MyAngularScripts/motorola-xoom-with-wi-fi.json.htm
, a 404 not found error is generated.

How can I update my Service to accommodate two different URLs?

Current Service code:

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

phonecatServices.factory('Phone', ['$resource',
  function ($resource) {
      return $resource('/MyAngularScripts/:phoneId.json.htm', {}, {
          query: { method: 'GET', params: { phoneId: 'jsonPhonedata' }, isArray: true }
      });
  }]);

Current controller code for retrieving phone list: $scope.phones = Phone.query();

Current controller code for retrieving details of selected phone:

 $scope.phone = Phone.get({ phoneId: $routeParams.phoneId }, function (phone) {
      $scope.mainImageUrl = phone.images[0];
  });

How should I adjust the controller code to invoke the services accordingly?

Answer №1

A customized URL can be assigned to each action.

 return $resource(
           "/MyAngularScripts/:phoneId.json.htm",
           { Id: "@Id" },
           {
               'get':{url:'/CustomContent/Phone/'+:phoneId+'data.json'},
               'query' : {url:'/MyAngularScripts/phones.json'},
           }
      );

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

`How can we efficiently transfer style props to child components?`

Is there a way to pass Props in the Style so that each component has a unique background image? Take a look at this component: countries.astro --- import type { Props } from 'astro'; const { country, description } = Astro.props as Props; --- & ...

PascalCase causes Json.Net roundtrip to fail

Here is a scenario where a certain class successfully roundtrips (serialized to string, then deserialized to object): public class FooClass { public readonly IFileLocation File1; public readonly IFileLocation File2; public readonly IFileLocati ...

Parsing an array of JSON objects retrieved from a JSON response

I received a JSON response that has the following structure: "corps": [ { "id": "1007", "company_id": "1007", "org_name": "My organization 1", "org_addr1": "123 W. 1234 S.", "org_addr2": "", }, { "id": "1008", "org_name": "My organization 2", "org_addr1": ...

What is the process for assigning an id to a div in order to make comparisons in React?

After attempting to assign an id to a div for comparison, an error was thrown indicating that "id is not defined". Here is the data: https://i.sstatic.net/PZjDk.png And here is the function: https://i.sstatic.net/y4MEB.png I attempted to add an id attri ...

How come the use of a timeout causes the this variable to seemingly lose its reference?

What is the reason why this: myelements.mouseenter(function() { clearTimeout(globaltimeoutvar); globaltimeoutvar = setTimeout(function() { var index = myelements.index(this); console.log(index); // -1 }, 150); }); Returns -1, while this: m ...

Substitute the attributes of one object with those of another

Alright, I'm revising this because it seems to be causing confusion. Imagine you have two items x and y. What I aim to do is swap all the characteristics of x with those of y. (Please note that this isn't your usual duplication process where a ...

Using Jquery to encase an element in a div while scrolling down and removing it while scrolling up

After some experimentation, I've managed to wrap an element inside a div using jQuery. My next challenge is to wrap it as you scroll down and unwrap it as you scroll up. Do you think this is achievable? Although I have succeeded in wrapping it while ...

What is the best way for Cucumber to move on to the next annotation only after ensuring all async requests from the previous one have finished processing?

I am looking to set up a basic test using Selenium and Cucumber for logging into my web application and confirming that the main page is displayed correctly. Currently, all three tests are returning true even before the page is fully loaded. The issue ar ...

Is it possible to swap images by clicking on them?

Let's say I'm working with 3 images. Image A, B and C. A is the main image initially. If I click on image B, it will become the main image and image A will take its place in the old position. The same condition applies when B is the main image a ...

"Implementing a filter with multiple select options in AngularJS

As a beginner delving into Angular, I find myself working with a multiple select feature to filter a list by name. <select multiple ng-options="data.name for data in datas" ng-model="filterData"> </select> Currently, I am able to filter with ...

MongoDB error codes and their associated HTTP status codes are important for developers to understand

When a new user attempts to sign up with an existing user account, MongoDb triggers a 11000 error code In Express, handling this scenario can be done as follows: async function signup(req, res, next){ try{ // perform some actions }catch(err){ i ...

Conditionally displaying an input model in Vue.js using v-if

Just starting to learn vue.js and I'm looking to display table data. My idea is that when the table is in display mode, it should only show the data. However, when I click on the edit button of a table row, I want that specific row to switch to edit m ...

What is the best way to retrieve user data for showcasing in a post feed using firebase's storage capabilities?

I'm currently developing a forum-style platform where users can share content that will appear on a universal feed. I intend to include user details in the posts (such as photoURL and displayName) similar to how it is done on Twitter. For this projec ...

Having trouble with Vue 3 Composition API's Provide/Inject feature in Single File Components?

I am currently developing a VueJS 3 library using the Composition API. I have implemented Provide/Inject as outlined in the documentation. However, I am encountering an issue where the property in the child component remains undefined, leading to the follo ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

What steps can I take to troubleshoot issues when creating a React app?

While attempting to set up a react application using npx create-react-app projectreact, I encountered the following error message: PS C:\Users\ahnaa\OneDrive\Documents\Web Developent\Reaact JS> npx create-react-app project ...

What is the process for converting x and y coordinates to align with a fixed display?

When I make an API call, I am receiving X and Y coordinates in the following format: x: "-0.0120956897735595703" y: "0.147876381874084473" To display these coordinates on my minimap images, I have set their display to be absolute. The "left" and "top" pr ...

Exploring deep layers of data in YAML/JSON using Handlebars

My YAML structure is as follows: props: MY_NAME: value: '2px' meta: css: 'padding' Currently, I am attempting to retrieve values using Handlebars in the following way: { "props": [ {{#each props as |prop|} ...

When integrating string variables into JavaScript regular expressions in Qualtrics, they seem to mysteriously vanish

I have been working on a project to analyze survey responses in Qualtrics by counting the number of matches to specific regular expressions. For example, whenever phrases like "I think...", "In my opinion," are used, the count increases by one. Below is t ...

What is the best way to define a dynamic model name in AngularJS?

I am looking to dynamically populate a form with custom questions (check out the example here): <div ng-app ng-controller="QuestionController"> <ul ng-repeat="q in Questions"> <li> <div>{{q.Text}}</div> ...