我正在做一个在线教程,他们教你使用 MEAN 制作一个简单的网络应用程序。下面的代码用于编辑给定的 JSON 对象集合(这里的视频是 JSON 对象)
该集合位于
/api/videos
因此,我必须单击 href="/#/video/{{video._id}}
,它会将我带到 form.html,并且我可以选择编辑“标题”和“描述” ' JSON 对象的参数。
我似乎无法理解的是:
a)为什么需要这个(问题中的完整代码)
var Videos = $resource('/api/videos/:id', { id: '@_id' },
{
update: { method: 'PUT' }
});
由于我在 href="/#/video/{{video._id}}
上,所以我不能直接从 URL 中获取 ID
var Videos=$resource('api/videos)
Videos.get({ id: $routeParams.id }, function(video){
$scope.video = video;
});
b)工作流程是什么(即何时发出 router.get() 请求以及何时发出 router.put() 请求) 根据我的说法,当我单击“保存”按钮时, Controller 会向 API 发出 put 请求,但我无法弄清楚 router.get() 请求何时发出
我正在尝试阅读 Express 和 Angular 文档,但它们似乎没有解释工作流程。 您能否告诉我应该阅读哪些内容才能更好地理解?
这是form.html代码
<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>
这是 Controller 代码
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('/');
});
}
}]);
这是 API 端点代码
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);
});
});
最佳答案
嗯,根据AngularJS docs for $resouce ,$资源是:
A factory which creates a resource object that lets you interact with RESTful server-side data sources.
换句话说,是RESTful服务操作的快捷方式。下面的代码创建了一个带有 API 端点的接口(interface),以使 REST 操作更容易执行。 一旦你有了这个:
var User = $resource('/user/:userId', {userId:'@id'});
这样做要容易得多:
User.get({userId:123}, function(user) {
user.abc = true;
user.$save();
});
因为RESTful是一个标准,而$resource
是Angular对该标准中API的消耗的实现。在他的内部,根据您配置和选择的操作,使用适当的 header 和方法发出异步请求。
关于javascript - 我无法理解这段代码的工作流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39963740/