【发布时间】:2017-06-15 08:28:07
【问题描述】:
我正在尝试对 API 接口进行多次 $http 调用以更新我的模型。
让我解释。我想将一个新对象保存到我的数据库中,一旦保存了该对象,我想取回该对象并执行另一个 $http 调用来更新另一个对象。这是我的代码:
型号:
var departmentSchema = mongoose.Schema({
username : { type:String,unique:true,required:true},
email : { type:String,unique:true,required:true},
name : { type:String, default:"", unique:true,required:true},
stations : {
type: [mongoose.Schema.Types.ObjectId],
ref: 'Station'
}
})
// Method that Pushes a Station to the department
departmentSchema.methods.pushStation = function(station) {
var department = this;
department.stations.push(station)
};
API 路由
router.put('/departments/:dep_id/stations/:stat_id', function(req, res, next) {
Station.findOne({_id: req.params.stat_id}, function(err, data1){
if (err) { return next(err); }
var station = data1;
Department.findOne({_id: req.params.dep_id}, function(err, data2){
if (err) { return next(err); }
var department = data2;
department.pushStation(station)
res.json({success:true, department:department});
});
});
});
Angularjs $http 缩进调用
$scope.addNewStation = function(station){
$http.post('/api/stations/', station)
.then(function (data) {
console.log(data)
$scope.station = data.station;
$http.put('/api/departments/' + $scope.department._id + '/stations/' + $scope.station._id, $scope.station)
.then(function (data) {
console.log(data);
})
bootbox.alert("Station Created Successfully");
},function (err) {
console.log(err)
})
}
我应该指出,我的 URL 中有 $scope.department,这是因为我从之前的调用中获取了该数据,并且我不想在这部分添加不必要的代码。
所以问题是当我执行$scope.addNewStation(...) 时,我能够成功添加新站,出现引导箱警报,显示第一个console.log(data),但随后我在控制台上收到错误消息:TypeError: Cannot read property '_id' of undefined 和第二个console.log(data) 没有出现。
请告诉我我在这里做错了什么。我真的需要帮助。谢谢。
【问题讨论】:
-
对不起。看不到 scope.department._id 设置在哪里
-
为什么不使用“瀑布”而不是嵌套调用? Here's a link
-
嘿@federicoscamuzzi,就像我上面解释的那样,$scope.department 是一个从先前调用返回的对象。该对象包含 $scope.department._id。所以只要假设它就在那里。
-
嘿@DavidStensrøm 你能给我一个你在说什么的例子吗?谢谢。
-
@AllJs
console.log(data)显示了什么?它可能没有station属性... 编辑:实际上,$http.post返回一个响应对象,您应该这样做$scope.station = data.data.station
标签: javascript angularjs node.js api http