Exploring the relationship between $resource and controllers

I am currently working on deciphering the code snippets below. From what I gather, there are three resource objects - CategorySrv, ArticleSrv, and SearchSrv that interact with REST server data sources.

app.factory('CategoryService', function($resource) {
    return $resource('categories');
});

app.factory('ArticleService', function($resource) {
    return $resource('articles');
});

app.factory('SearchService', function($resource) {
    return $resource('articles/search');
});

My question is: when does the controller's code execute? It seems like it only runs once when the page loads. When will it run again? As far as I know, the controller's code doesn't run in a loop but is called either when its methods are invoked from the view or when the section of the page associated with this controller is loaded.

When triggered, the listed resource objects are passed as arguments and the controller's function is executed:

app.controller('AppCtrl', function($scope, $location, CategoryService, ArticleService, CartService) {


CategoryService.query(function(response) {
    $scope.categories = response;
});

ArticleService.query(function(response) {
    $scope.articles = response;
});

CartService.get(function(response) {
    $scope.cartInfo = response;
});

Am I interpreting this correctly? And could you explain the difference between using get and query in the above context?

Answer №1

Absolutely. The code will only execute once, when the controller is loaded.

When using $resource, you have the choice between utilizing get or query. The main difference lies in that query will immediately return an empty array or object based on whether isArray is set to true. This feature helps prevent errors from occurring during rendering, avoiding situations where Angular anticipates an array or object but receives undefined (as in cases of asynchronous actions). Upon receiving a response with data, the digest cycle will trigger as changes in $scope are detected, subsequently refreshing your view.

For more information, refer to the documentation: https://docs.angularjs.org/api/ngResource/service/

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

Invoking a function of a Redux-form React component

Is there a way to access the component method of a redux-form? I want my upload button to submit the form and also open the file select dialog if the user hasn't selected any file. Here is my code: UploadModal.js import React from 'react&apos ...

Using next.js and redux for user authentication: a step-by-step guide

After creating my next.js app with version 9.3.5, the authentication was working perfectly. However, after updating next-redux-wrapper and next.js, I noticed that when I refresh the page, the user is no longer authenticated even though the cookie still exi ...

Issue with Promise rejection not being caught in Node.js with ExpressNode.js and Express are not

Within my Express web application, I've created a function that outputs a Promise object. login: function(un, pass) { result = {}; var loginOk = new Promise( function (resolve, reject) { if (result.hasOwnPr ...

I'm experiencing some issues with AwaitingReactions in Discord.js, it's not working properly on

I'm having trouble with implementing reaction awaiting as per the guide in discord.js. For some reason, it just doesn't seem to work on my end. No matter what I try, when I click the emoji, it doesn't register. I've scoured numerous Sta ...

Simple methods to minimize the iteration of array loops in Node.js

First, retrieve the "grid_id" from the "grids" array ( Step 1 ) Next, verify if this "grid_id" is present in the "variationsDB" array ( Step 2 ) Once you have this "grid_id", use it to fetch the "var ...

Can you explain the concept of an anonymous block in JavaScript ES6 to me?

Recently, I came across an article on pragmatists which discussed some interesting ES6 features. However, one concept that caught my attention was the use of an anonymous block within a function. function f() { var x = 1 let y = 2 const z = 3 { ...

Angular.js: Tips for creating a flexible 'modal' component with dynamic templates and controllers

Looking for suggestions on the best way to handle this situation. Currently, I have a DOM element in my application that functions as a modal by appearing from the right side of the viewport. Within various controllers in the app, I need the ability to loa ...

How come it's not possible to modify the text of this button right when the function kicks off?

When I click a button, it triggers a JavaScript function. The first line of code within the function uses jQuery to change the HTML of the button. However, the button's text does not update in the browser until after the entire function has completed, ...

What is the best way to combine objects that share the same id?

View Image: Displaying Image POST ID's https://i.stack.imgur.com/JO5OF.png I attempted to resolve this using jQuery each, but I am uncertain about the next steps. Check out my Code: jQuery(document).ready(function($) { var data, exampleData, , ...

Retrieve data from an array of objects nested within another object

Imagine a scenario where there is an object containing an array of objects. let events = { "id": 241, "name": "Rock Party", "type": "party", "days": [ { "i ...

What is the best way to relocate an image or link using CSS?

I've been attempting to adjust the position of this image using CSS, but no matter how many times I try, it just refuses to budge. Can someone please help me troubleshoot what might be causing this issue? #yahoo1 { position: absolute; top: 100p ...

What is the behavior of a variable when it is assigned an object?

When using the post method, the application retrieves an object from the HTML form as shown below: code : app.post("/foo", (req, res)=> { const data = req.body; const itemId = req.body.id; console.log(data); console.log(itemId); }) ...

Wait for the successful $save in AngularJS before redirecting

How can I redirect to my list page after POSTing a form if there are no errors and the data is successfully saved in the database? app.controller('NoteCreateController', ['$scope', 'Note', '$routeParams', '$l ...

`Angular RxJS vs Vue Reactivity: Best practices for managing UI updates that rely on timers`

How can you implement a loading spinner following an HTTP request, or any asynchronous operation that occurs over time, using the specified logic? Wait for X seconds (100ms) and display nothing. If the data arrives within X seconds (100ms), display i ...

Retrieve Data from Form Using PHP and Ajax

I currently have a form on my HTML page that looks like this: <form id="submission" action="testresponse.php" method="post"> <input id="URL" name="URL" type="text"> <button name="Submit" type="submit">Subm ...

Customizing blockquote styling in QuillJS with a unique class

Currently, I am exploring a method to include a custom class when the user selects the blockquote toolbar button. When the blockquote is clicked, it generates the following element: <blockquote class="ql-align-justify">this is my quoted tex ...

A novel way to enhance a class: a decorator that incorporates the “identify” class method, enabling the retrieval

I have been given the task to implement a class decorator that adds an "identify" class method. This method should return the class name along with the information passed in the decorator. Let me provide you with an example: typescript @identity(' ...

Using AngularJs to create a couchdb document

const post_data = { "task_list": $scope.task_list, "uri": $scope.uri }; $http({ method: 'POST', url: 'http://127.0.0.1:5984/tasklist/' + $scope.task_list, data: post_data }) .success(function(data, status, headers, config) { ...

Utilizing Regular Input with Material-UI's Autocomplete Feature

Is there a way to replace TextField with a regular input in an Autocomplete? ...

What is the response of Express when it encounters numerous identical asynchronous requests from the same origin?

Currently, I am utilizing Express.js for my project. There is an async function that performs a task that can take anywhere from 20 to 30 seconds to complete. Once the task is done, it increases a user's counter in the database. However, users are req ...