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);
});
});