获取EJS模板中的项目ID并注入服务

我想弄清楚如何传递一个Id到我的PlayerDetailController ,然后在我的服务中使用它。

我在我的主app.js有以下路线:

 var players = require('./routes/players'); app.use('/players', players); 

我在players路线( routes/players.js )中有以下路线:

 var express = require('express'); var router = express.Router(); /* GET /players listing. */ router.get('/', function(req, res, next) { res.render('players', { title: 'Players', action: 'list'}); }); /* GET /player details. */ router.get('/:id', function(req, res, next) { res.render('players', { title: 'Player Details', action: 'details'}); }); module.exports = router; 

以下是我主要的players.ejs模板:

 <!-- other layout elements --> <% if (action === 'details') { %> <% include partials/players/details %> <% } else if (action === 'update') { %> <% include partials/players/update %> <% } else if (action === 'remove') { %> <% include partials/players/remove %> <% } else { %> <% include partials/players/list %> <% } %> <!-- other layout elements --> 

而我deatils.ejs部分:

 <div ng-controller="PlayerDetailsController"> <div class="playerDetails"> <p> <strong>{{ player.name}} - {{ player.position }} - {{ player.team }}</strong><br/> Touchdowns: {{ player.touchdowns }}<br/> Yards: {{ player.yards }} </p> </div> </div> 

而我的PlayerDetiails服务:

 // PlayerDetails Service app.factory('PlayerDetails', ['$http', function($http){ // below is where I'm trying to inject the Id return $http.get('/api/player/:id'); }]); 

但我不知道如何将我的path中显示的Id(例如http://localhost:3000/players/550130d32f3345bc065f2ecfhttp://localhost:3000/players/550130d32f3345bc065f2ecf到我的控制器,以便我的控制器调用并接收正确的播放器数据。 我将如何做到这一点? 我以为我可以添加一个id属性res.render调用,但我不知道我会怎么做在EJS模板。 任何帮助将不胜感激!

       

网上收集的解决方案 "获取EJS模板中的项目ID并注入服务"

将ID传递给您的模板:

 router.get('/:id', function(req, res, next) { res.render('players', { title: 'Player Details', action: 'details', id: req.params.id}); }); 

ng-init收到id:

 <div ng-controller="PlayerDetailsController" ng-init="id = <%= id %>"> 

PlayerDetails服务:

 app.service('PlayerDetails', ['$http', function($http){ return { get: function(id) { return $http({ url: '/api/player/:id', params: {id: id}, method: 'GET' }); } }; }]); 

PlayerDetailsController中的某处:

 // id is from ng-init PlayerDetails.get($scope.id).success(function(player) { $scope.player = player; }).error(function(error) { console.error(error); }); 

传递给路由的ID将在req.params.id可用。 您可以使用ID从数据库中检索播放器,并将该对象传递给视图。

像这样,使用mongooseODM。 如果你正在使用另一个数据库/ ODM / ORM的代码将是不同的,但想法是一样的:

 /* GET /player details. */ router.get('/:id', function(req, res, next) { Player.find({ _id: req.params.id }, function(err, player) { if(err) return next(err); res.render('players', { title: 'Player Details', action: 'details', player: player }); }); }); 

然后你可以通过player属性访问Player文件。

如果你想创build一个能以JSON格式返回所有玩家数据的API,你可以这样做:

 /* GET /api/player/:id */ router.get('/:id', function(req, res, next) { Player.find({ _id: req.params.id }, function(err, player) { if(err) return next(err); res.json(player); }); });