我是nodejs和angularjs的新手,希望我能在这里得到一些帮助。 我正在尝试创建一个小型的学习应用程序。我正在使用angularjs,Mongodb和nodejs。 我如何根据特定的想法id查询问题,使用以下给定的参数传递? 我有以下内容:我创建了问题服务和创意服务:
app.factory('Problem',
['$rootScope', '$resource',
function ($rootScope, $resource) {
return $resource($rootScope.apiBaseURL + '/problems/:id', {id:'@id'}, {
update: {
method: 'PUT'
}
});
}]);
我也有问题控制器:
app.controller('ProblemController', [
'$rootScope','$scope', 'Problem',
function ($rootScope,$scope, Problem) {
//$scope.htmlVariable = 'Explain why you selected this problem… What is the need that you are trying to fulfill?(Please make sure to limit your answer to 140 Words)';
$scope.problem = Problem.query();
}]
后端:
use strict';
// modules dependencies
var mongoose = require('mongoose'),
Problem = mongoose.model('Problem');
/**
* create problem
*/
exports.create = function (req, res) {
var newProblem = new Problem(req.body);
newProblem.save(function(err) {
if (err) return res.status(400).send(err)
res.json(newProblem);
});
};
/**
* update problem
*/
exports.update = function (req, res) {
//TODO check token
};
/**
* get problem by id
*/
exports.getById = function (req, res) {
Problem.findById(req.params.id, function (err, problem) {
if (err) return res.status(400).send(err)
if (problem) {
res.send(problem);
} else {
res.status(404).send('Problem not found')
}
});
};
/**
* get all problems
*/
exports.getAll = function (req, res) {
Problem.find(function (err, problems) {
if (err) return res.status(400).send(err)
res.send(problems);
});
};
);
问题架构:
'use strict';
// modules dependencies
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
// model
var ProblemSchema = new Schema({
description: {
type : String,
unique : false,
required : false
},
creator: {
type : Schema.Types.ObjectId,
unique : false,
required : true,
ref : 'User'
},
idea: {
type : Schema.Types.ObjectId,
unique : false,
required : true,
ref : 'Idea'
}
});
mongoose.model('Problem', ProblemSchema);
路线:
// problem routes
var problemController = require('../controllers/problemController');
router.post ('/problems', authController.isBearerAuthenticated, problemController.create );
router.put ('/problems/:id', authController.isBearerAuthenticated, problemController.update );
router.get ('/problems/:id', authController.isBearerAuthenticated, problemController.getById);
router.get ('/problems', authController.isBearerAuthenticated, problemController.getAll );
答案 0 :(得分:1)
您正在尝试异步调用一段时间后哪些数据可用。您需要在$resource
承诺中获取其数据,如下所示
Problem.query({id: 2}).$promise
.then(function(data){
$scope.problem = data;
});