This code's workflow is completely confusing to me

Currently, I am engaging in an online tutorial that focuses on creating a basic web application using MEAN stack. The coding snippet provided below pertains to the modification of a collection of JSON objects (where videos are represented as JSON objects).

The specific collection can be located at: /api/videos. To proceed with editing, I need to click on a link like href="/#/video/{{video._id}}, redirecting me to form.html where I have the flexibility to alter the 'title' and 'description' attributes of the JSON object.

One aspect puzzling me is:

var Videos = $resource('/api/videos/:id', { id: '@_id' },
         {
            update: { method: 'PUT' }
        });
    

Given that I am already on href="/#/video/{{video._id}}, couldn't I directly extract the ID from the URL?

var Videos=$resource('api/videos)   

Videos.get({ id: $routeParams.id }, function(video){
            $scope.video = video;
        });
    

Secondly, what exactly is the workflow? When does the router.get() request occur and when does the router.put() request take place?

My presumption is that upon clicking the save button, the Controller initiates a PUT request to the API. However, understanding when the router.get() request triggers remains unclear.

I am currently immersing myself in the documentation for Express and Angular, seeking clarity on the workflow. Could someone guide me on additional resources for gaining deeper insight?

This section entails the form.html code:

<h1>Add a Video</h1>

<form>
    <div class="form-group">
        <label>Title</label>        
        <input class="form-control" ng-model="video.title"></input>
    </div>
    <div>
        <label>Description</label>
        <textarea class="form-control" ng-model="video.description"></textarea>
    </div>
    <input type="button" class="btn btn-primary" value="Save" ng-click="save()"></input>    
</form>
    

Below showcases the controller code:

app.controller('EditVideoCtrl', ['$scope', '$resource', '$location', '$routeParams',
    function($scope, $resource, $location, $routeParams){   
        var Videos = $resource('/api/videos/:id', { id: '@_id' },
         {
            update: { method: 'PUT' }
        });

        Videos.get({ id: $routeParams.id }, function(video){
            $scope.video = video;
        });

        $scope.save = function(){
            Videos.update($scope.video, function(){
                $location.path('/');
            });
        }
    }]);
    

Last but not least, here's the API Endpoint Code:

router.get('/:id', function(req,res){
    var collection =db.get('videos');
    collection.findOne({_id: req.params.id},function(err,video){
        if(err) throw err;
        res.json(video);
    });
});
router.put('/:id', function(req, res){
     var collection=db.get('videos');
     collection.update({_id:req.params.id},
     {title: req.body.title,
     description: req.body.description
     },
     function (err,video)
     {if (err) throw err;
        res.json(video);
     });
 });
    

Answer №1

As stated in the AngularJS documentation for $resource, $resource serves as:

A tool that generates a resource object enabling interaction with server-side data sources following the principles of REST architecture.

In simpler terms, it acts as a convenient shortcut for handling RESTful service operations. The example below showcases how to establish an interface with an API endpoint for streamlined REST operations.

var User = $resource('/user/:userId', {userId:'@id'});

This makes tasks like the following much more straightforward:

User.get({userId:123}, function(user) {
  user.abc = true;
  user.$save();
});

Since RESTful is a widely adopted standard, Angular's implementation of $resource simplifies the consumption of APIs in this format. Internally, it executes asynchronous requests with appropriate headers and methods based on your configured operation choices.

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

Exploring the capabilities of Angular and UIGrid for fetching table information

I have been utilizing Angular along with uigrid, which is an excellent library for displaying data in a tabular format. Everything looks good when displaying the table. However, when I update an item and click on a Save button that triggers a rest service ...

Transmit information from node.js to the frontend utilizing only raw JavaScript

Seeking guidance on sending data object from a Node.js server to a JS file for frontend use. In the main.js file, DOM manipulation is performed. The following request is made: let dataName = []; let request = async ('http://localhost:3000/') =& ...

Total of Vue Component Subtotals

One of the challenges I'm facing in my Vue app is calculating the total of subtotals. Every component has its own subtotal that depends on user input. I need to combine these individual subtotals and display the result in an input field outside of th ...

Attempting to load the parent window of a framed page from a separate domain results in a permission denial issue in Internet

Having an issue with a login page that is hosted within an iframe on a different domain. After a successful login, I am attempting to load the following page: <html> <head> </head> <body onload="parent.window.loca ...

"Learn the process of extracting information from a database and exporting it to a CSV file with Angular 2

Currently, I am facing an issue where I need to retrieve data from a database and export it to a CSV file. While I am able to fetch all the data successfully, I am encountering difficulty when trying to fetch data that is in object format as it shows up as ...

App.controller attributes in HTML tags are not receiving the value of the HTML variable

In the process of developing a simple student-teacher web application, I am utilizing AngularJS to handle the front-end. Within my JavaScript file, there are two app controllers - one for fetching student data and another for retrieving subjects assigned t ...

Please ensure that the table is empty before reloading data into it

I am facing an issue while binding data from the database. The data is being bound every 5 seconds, however, it does not clear the previous data and keeps accumulating. Instead of displaying just 3 rows when there are 3 in the database, it adds 3 rows ev ...

Modifying background image with Javascript

I've been working on developing a slideshow for one of the web pages I'm building. To achieve this, I set up a div with a unique class name that allows me to change the background image using JavaScript. Here's what I've accomplished so ...

When the page loads, sorting by numbers will automatically occur without requiring a click event

Hey there! I've got a modal set up for displaying event details like the one shown in this image: https://i.sstatic.net/73xTW.png Within this modal, users have the option to accept, reject, or leave events pending. In our API, the status values corre ...

Identify the moment a dialogue box appears using jQuery

I'm facing a situation where multiple dialogs are opened in a similar manner: $("#dialog").load(URL); $("#dialog").dialog( attributes, here, close: function(e,u) { cleanup } The chall ...

Swap out periods with commas in the content of Json Data

I have a JSON file containing percentage data that I am extracting and displaying on my website: <?php $resultData = file_get_contents('https://example.com/json/stats?_l=en'); $jsonData = json_decode($resultData, true); if( isset( ...

I'm puzzled by the "Uncaught TypeError:" error message and can't seem to figure it out

I'm having trouble displaying the value of 'true' within my objects and keep encountering an error message. Uncaught TypeError: Cannot set property 'toDoIsRemoved' of undefined at removeTask (main.js:85) at HTMLButtonElemen ...

What could be causing the issue with updating a js file using ajax?

I've been dealing with a php file called users. Initially, everything was going smoothly as I wrote some JavaScript code for it. However, after making updates to the JavaScript code, it seems to have stopped functioning. Below is the content of the p ...

Issue with Angular form not triggering ng-submit functionI am facing a problem where

Issue with angular submission: I've been trying to implement a simple submission feature using angular, but the $scope.account_create.submit function isn't getting called upon submission. I have added the name attribute to the form and ensured th ...

Storing extensive JSON data with AJAX, jQuery, and Java

Currently, I am utilizing jQuery AJAX to call a server-side method and sending a JSON string to the controller. Everything works smoothly when the JSON size is small, but as soon as it exceeds 7kb, the server side rejects the JSON string. I suspect that t ...

Why isn't the dropdownlist setting a default value in Javascript?

<select id="modalAdd_DDLSample"> </select> <option value=0> PC</option> <option value=1> MAC </option> <option value=2> Rasberry </option> $("#modalAdd_DDLSample").val("1"); $("#modalAdd_DDLSample").val(1); ...

Unable to store the hashed password using bcrypt

I've been working on persisting hashed passwords using sequelize, bcrypt, and express. While the hash is being generated, it seems like the database entry occurs before the hash value is ready. My understanding of NodeJS is still in its early stages. ...

Having issues with Promise.resolve() not functioning as expected in a Jasmine test

I am currently working on setting up a test that involves promises. Below is the code snippet for reference: var promise; beforeEach(inject(function ($q) { promise = $q.resolve(); })); it('should resolve', function (done) { promise.the ...

New to WCF: How to Invoke Methods using JavaScript

Hello there! As someone new to WCF, I initially thought it would be similar to ASP.NET web services. However, I'm facing an issue where I am unable to call a method from client-side JavaScript. Here is a snippet of my web form: <form id="form1" r ...

Retrieve information from JSON dataset [object]

Click here for debugging screenshot $.ajax({ url: postUrl, type: 'GET', dataType: 'json', data: { "id": num }, contentType: "application/json; charset=utf-8", success: function (data) { $.each(data, ...