Efficiently accessing and displaying nested models in AngularJS

Currently, I am in the process of developing a website that involves numerous relational links between data. For instance, users have the ability to create bookings, which will include a booker and a bookee, as well as an array of messages that can be associated with a booking.

An illustration in JSON format would look like this...

booking = {
  id: 1,
  location: 'POST CDE',
  desc: "Awesome stackoverflow description."
  booker: {
    id: 1, fname: 'Lawrence', lname: 'Jones',
  },
  bookee: {
    id: 2, fname: 'Stack', lname: 'Overflow',
  },
  messages: [
    { id: 1, mssg: 'For illustration only' }
  ]
}

My main question is, how should one structure this data in an Angular app? Furthermore, how would you retrieve it from the server?

From my perspective, there are a few approaches.

Retrieve all data at once from the server

In this scenario, I would depend on the server to serialize the nested data and directly utilize the provided JSON object. The drawbacks here are that I wouldn't know which users are involved when requesting a booking or similar objects, making caching impossible, resulting in pulling a large amount of data each time a request is made.

Retrieve booking with booker/bookee represented as user ids

Here, I would employ promises for my data models and have the server send back an object like...

booking = {
  id: 1,
  location: 'POST CDE',
  desc: "Awesome stackoverflow description."
  booker: 1, bookee: 2,
  messages: [1]
}

This object would then be passed to a Booking constructor, where I would resolve the relevant (booker,bookee, and message) ids into data objects using their respective factories.

The downside here is that multiple ajax requests are made for a single booking request, although it allows for caching user/message information.


To summarize, is it best practice to rely on a single ajax request to gather all nested information at once, or use various requests to fill in additional details after receiving the initial response.

It's worth mentioning that I'm utilizing Rails 4 (maybe Rails would better suit a single request approach?)

Answer №1

In an effort to combine the best of both worlds, I am implementing a system where all my resources will have a base class with a custom resolve function. This function will identify which fields in each specific class may need resolution. An example resource function is outlined below...

class Booking
  # other methods...
  resolve: ->
    booking = this
    User
      .query(booking.booker, booking.bookee)
      .then (users) ->
        [booking.booker, booking.bookee] = users

This function will pass the values of the booker and bookee fields to the User factory, which has a constructor as follows...

class User
  # other methods
  constructor: (data) ->
    user = this
    if not isNaN(id = parseInt data, 10)
      User.get(data).then (data) ->
        angular.extend user, data
    else angular.extend this, data

If a value that cannot be parsed into a number is passed to the User constructor (accepts both string and numerical ids), it will use the User factory's get function to retrieve data from the server. If the value can be parsed into a number, it will assume the User object has already been serialized and extend the current object with the data provided.

This implementation handles caching invisibly and independently of how the server returns nested objects. It allows for modular ajax requests and prevents unnecessary data downloads through its caching system.

Once everything is set up, I will conduct tests to determine whether larger, chunked ajax requests or smaller modular requests, like the one described above, would serve the application better. Regardless, this approach ensures that all model data passes through angular factories, giving every record access to any prototype methods needed.

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

Load information from a JavaScript object when the user clicks dynamically

My challenge involves utilizing a JavaScript object that contains video information such as title and source URL. Within my HTML, I have image placeholders and the goal is to trigger a modal pop-up (using Twitter Bootstrap modal) of the specific video when ...

React: Despite my efforts to return a value from render, nothing was actually returned

My current project involves creating nested components to display the dataset I have. export const MyComponent = (props) => { const groupMilestoneByYear = (data) => { // Take Milestone Data array as input and group it by Year let yearGroup ...

Does the downloading of images get affected when the CSS file has the disabled attribute?

Is it possible to delay the download of images on a website by setting the stylesheet to 'disabled'? For example: <link id="imagesCSS" rel="stylesheet" type="text/css" href="images.css" disabled> My idea is to enable the link later to tri ...

Error: Attempting to access the 'clipboard' property on an undefined object results in a TypeError when invoking this.$q.electron.clipboard

I'm currently working on incorporating copy to clipboard functionality into my app using Electron. This is the command I am using: methods: { copyToClipboard () { if (process.env.MODE === 'electron') { this.$q.electro ...

Comparison of performance between virtual dom and dirty-checking

As a newcomer to the world of React, I am very curious about the performance differences between React's virtual DOM and Angular's dirty checking method. React utilizes a “diffing” algorithm. a. How does this algorithm work? b. Does it m ...

Dynamic menu bar accompanied by primary content

I'm facing an issue with my active navigation bar. Whenever I open the hamburger menu, the main content remains fixed and does not move along with the open navigation menu. I tried searching online for a solution but couldn't find anything helpfu ...

Ensure to preselect the radio button based on the Day's value

I have set up my Radio buttons with corresponding content to be displayed when clicked. I want to automatically pre-select the tab button based on the current day. For example, if today is Sunday, the page should load showing the contents for Sunday. If i ...

What is the best way to choose dropdown values by utilizing various button IDs?

I have four different vacation destinations and four buttons. I want to automatically select each destination separately when the corresponding button is clicked. <select class="aa" required="" name="f1990" {input.multiple}="" {input.size}="" id="f19 ...

Creating the jquery/javascript code needed to produce an event or alert similar to the "Confirm Navigation" prompt used on sites like Stack Overflow

Similar Question: How can I have a confirmation message when navigating away from a page after making changes? I've noticed an interesting feature on Stackoverflow: when you start writing a new question and attempt to leave the page, it prompts y ...

Display the Bootstrap datepicker within an h4 element set to default to today's date, utilizing both Angular and jQuery

Utilizing Boostrap datepicker to obtain the selected date from the calendar and insert it into an <h4> html tag. However, my goal is to display today's date by default in the h4 when it opens for the first time. Using angular.js + jquery f ...

Creating an object that tracks the frequency of each element from another object using JavaScript

I have a scenario where I need to create a new object based on the number of occurrences of specific minutes extracted from a timestamp stored in another object. Existing Object: { "data": { "dataArr": [ { ...

Saving decimal values in a React Material UI textfield with type number on change

I am currently working on a textfield feature: const [qty, setQty] = useState({ qty: "0.00" }); ..... <TextField required id="qty" type="number" label="Qtà" value={qty.qty} step="1.00& ...

What is the best way to utilize a variable retrieved from a mysql connection in NodeJS within an asynchronous function?

My current project involves scraping a website using Puppeteer. I am aiming to extract the date of the last post from my database and compare it with the dates obtained during the scrape. This way, I can determine if a post is already present in the databa ...

Personalized ES6 Bootstrap module created for a toggle switch button in Vue

Utilizing the custom switch toggle in a Vue application is my current task. Check out this link for more on the custom switch toggle I found a button that suits my needs, but I am unsure how to properly integrate it into my component so it can handle the ...

Is there a way I can create an object in JavaScript by using an array of values as parameters instead of having to manually list them out?

Can I achieve this? My goal is to develop a universal factory function that can generate different types of factories with some commonalities. I aim to pass arguments as an array to the base factory, which would then potentially create a new object instanc ...

Missing values in AJAX PHP parameter

Here is the URL that I am passing: "url=http://localhost.com/tenHsServer/tenHsServer.aspx?t=ab&f=DeviceStatus&d=C5" and here is the PHP file where I am entering it: <?php //set POST variables $url = $_POST['url']; unset($_POST[&apos ...

Utilizing the reduce() function to simultaneously assign values to two variables from data input

Looking to simplify the following function using reduce(), as the operations for variables selectedEnrolled and selectedNotEnrolled are quite similar. I attempted to use map(), but since I wasn't returning anything, it led to unintended side effects ...

Issue with JSON-to-MUI card mapping causing absence of UI components or error messages

I'm facing a challenge with mapping this JSON data to MUI Cards. Despite no error messages, the content isn't being displayed as expected. Surprisingly, when I make changes unrelated to the issue, the console.log(questionGroups) only shows the JS ...

LINT errors occur when $scope.method is assigned to the function method() {...}

Currently, I am working on understanding frontend concepts related to Angular. For my projects, I rely on a Yeoman generator to set up Angular/Gulp setups. The issue I am facing is as follows: PS P:\projects\trax> gulp test [19:35:22] Using ...

Tips on storing form data in AngularJS with the Fat Free framework

I am encountering an issue while trying to save data in SQL using Fat Free Framework. I have implemented the front end in AngularJS and I am sending data through an Angular ng-submit button. The AJAX POST request is being made but the data is not getting ...