Get the data linked to a specific identifier using AngularJS

I encountered an issue while developing a mobile app with angularjs.

During a request to retrieve a book object, I noticed a field named book_category, which holds the category ID for the book.

To display the name of the category instead of just the ID, I need to make another request to fetch the associated category. Essentially, I require a SQL JOIN-like operation.

This is how I structured my controller:

booksControllers.controller('BookDetailCtrl', ['$scope', '$routeParams', 'Book', 'Category',
    function($scope, $routeParams, Book, Category) {
        var book = Book.get({id: $routeParams.bookId});
        $scope.book = book;
        $scope.category = Category.get({categoryId: book.book_category});
}]);

Here's the relevant service code:

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

booksServices.factory('Book', ['$resource',
  function($resource){
    return $resource('http://****.herokuapp.com/books/:id.json', {}, {});
}]);

booksServices.factory('Category', ['$resource',
  function($resource){
    return $resource('http://****.herokuapp.com/categories/:categoryId.json', {}, {});
}]);

The issue arises when AngularJS expects an object but receives an array. This happens because AngularJS sends a request to categories.json instead of something like categories/<id>.json, despite providing the necessary categoryId.

Is there any way to work around this problem?

Thank you

Answer №1

Keep in mind that the requests are being handled asynchronously.

When you use the Book.get() method, it will not immediately return a fully populated object. Instead, it gives you an empty reference object that will be filled with data later on (refer to the documentation). Therefore, if you then call Categories.get() right after, you are passing an empty object for the id.

The documentation also mentions that the resource objects include a $promise property, which resolves once the query is complete.

With this in mind, you can implement the following:

// Utilize the promise from the previous API call
book.$promise.then( function() {
  // This code executes when the book object is fully populated.
  $scope.category = Category.get({categoryId: book.book_category});
});

I am unable to verify this without a plunkr and I lack experience with $resource. Please inform me of the outcome!

Answer №2

async function named get requires a callback to be called for execution. An example of implementing this is:

Book.get({id: $routeParams.bookId}, function(book) {
    $scope.book = book;
    Category.get({categoryId: book.book_category}, function(category) {
        // manipulate category data here
    });
);

To learn more, refer to the documentation for $resource here.

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

The Material multi select is unable to show the chosen name values at this time

I'm utilizing the Material Multiple select feature to pick employees, and you can see it in action on this demo: sandbox demo However, instead of displaying the ID values of the selected employees, I want to display their names. To achieve this, I t ...

The top scrolling behavior on click applies exclusively to the first set of Bootstrap 5 tabs

I am experiencing an issue with my HTML webpage that contains multiple BS5 Nav Tabs. The first tab is not functioning properly, while all the other tabs are working smoothly. When I click on the first BS5 Nav Tab, the page scrolls to the top with the addre ...

Embark on the journey of incorporating the Express Router

My Nodejs server is set up with router files that use absolute routes for the HTTP methods, such as /api/users/all. // /routes/user.routes.js module.exports = (app) => { app.use((req, res, next) => { res.header( "Access-Control-All ...

Returning back leads to disruption in change detection within Angular elements

I have been utilizing Angular elements for integrating my components into custom widgets on ThingsBoard. The process involves creating elements within the ngDoBootstrap() method as shown below: const newCustomElement = createCustomElement(CustomElementComp ...

Is there a way to search for a particular object within an array of data?

I recently started diving into the world of programming and I'm facing a challenge. I have an Array consisting of 4 items (you can view the Array in the Code section below), each item having its own id (1-4). What I aim to achieve is creating a metho ...

Deactivate particular months within the JqueryUI date picker

I'm currently working on a booking form that involves the jQuery UI Datepicker. I've encountered a major issue that I could use some assistance with: There are certain trips where only specific days are available for booking, and these trips can ...

jQuery - accessing a different class within the object

Let me explain the scenario: I have a website that will delve into 4 different subjects. Initially, I have 4 divs each representing the title of those subjects. For instance, <div><p> Physics </p></div> <div><p> Chem ...

Choose a sibling element using CSS styling

As I'm developing an AngularJS component, I am on the quest to identify ANY sibling of a particular tag, irrespective of whether they are div, span, or p. I'm hoping for a CSS-native solution that resembles something along the lines of div:siblin ...

Is it possible to generate a unique name from an array without any repeats?

Update: I am not looking to create a single list, but rather a button that generates a random name when clicked. Objective: Generate a random name from an array by clicking a button. The goal is to display one name at a time randomly without repetition. W ...

Incorrect naming in JSON response from REST API service

Currently, I am in the process of developing a web application using AngularJS and TypeScript with a Netbeans RESTful backend. I have created a TypeScript interface for a vendor which looks like this: interface Vendor { vendorno: number, name: str ...

Tutorial on connecting an object with a button in ASP.NET using the C# Tag property emulation technique

Currently developing an ASP.NET Point of Sale system, I am utilizing an AJAX tab container on my form to dynamically load all products from my database as buttons. private void AddProductsToTab() { int i = 1; foreach (AjaxControlToolkit.TabPanel t ...

ng-model not syncing with ng-options choice

I've spent a lot of time researching and troubleshooting this issue, but I can't seem to find a solution. Whenever I choose an item from the dropdown menu, it doesn't bind to my ng-model="chosenVariant". The console always shows that $scope. ...

There seems to be a problem with the bundle.js file caused by Uglify

I've just finished a project and now I'm ready to start building it. Utilizing a boilerplate project, I still find myself struggling to comprehend all the npm/webpack intricacies happening behind the scenes. Whenever I try to run "npm start", I k ...

Utilize the json_encode() function to convert a value into its JSON representation within a PHP file

I require assistance in utilizing json_encode() correctly to retrieve a JSON representation of a value within my PHP server script. From what I have learned, this cannot be achieved through echo, print, or loops, as discussed in other sources I've res ...

What is the most effective method for transforming a space-separated list of classes into a jQuery selector?

Is there a quick and efficient method for converting a space-separated list of classes like: classOne classTwo classThree into a selector such as: $('.classOne .classTwo .classThree') I am considering utilizing either a loop to construct a se ...

What could be causing the divs to overlap? Without the use of floats or absolute positioning,

When resizing vertically on mobile, my date-time-container is overlapping the upper elements welcome and weather. Despite setting them as block level elements, adding clear: both, and not using absolute positioning or floats, the overlap issue persists. An ...

My code includes a function that uses setInterval to generate graphs

Is there a way to stop the setInterval function without causing the graph to disappear? I've noticed that when the setInterval stops, the last 7 points plotted on the graph disappear. How can I prevent this from happening? Any suggestions would be gre ...

What is the best way to allow someone to chain callback methods on my custom jQuery plugin?

My goal is to enhance the functionality of jQuery.post() by implementing a way to check the response from the server and trigger different callbacks based on that response. For instance: $("#frmFoo").postForm("ajax") .start(function () { showSpinner( ...

Absence of environment variables in getServerSideProps within Next.js 13 independent deployment

Currently, I'm facing an issue where the props of my pages are not being hydrated properly. This problem arises as I migrate from an older version of NextJS and is where I find myself stuck at the moment. While everything seems to be working fine in d ...

Retrieve specific information using the identifier from the URL parameters during server-side rendering

I am trying to fetch data with a parameter from the URL using Nextjs. However, I am facing an issue where the parameter value is undefined. Here is the code snippet: const Room = () => { let fetchData; let roomId; const getID = () => { con ...