[英]Indented $http calls with AngularJS
我試圖在 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)
};
接口路由
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)
沒有顯示。
請告訴我我在這里做錯了什么。 我真的需要這方面的幫助。 謝謝。
.then()
回調中的對象是一個響應對象,它包括狀態、數據等屬性。 您應該按照以下方式做一些事情:
$http.post('/api/stations/', station)
.then(function(response) {
$scope.station = response.data.station;
})
使用 angular promise 試試這個,同時檢查范圍變量 station 和 department 是否正確初始化。
var promise = $http.post('/api/stations/', station);
promise.then(
function(data) {
$scope.station = data.station;
console.log($scope.station, $scope.department);
$http.put('/api/departments/' + $scope.department._id + '/stations/' + $scope.station._id, $scope.station)
.then(function (data) {
console.log(data);
});
});
我建議使用異步瀑布。
這是一個示例(在后端):
var waterfall = require('async-waterfall');
waterfall([
function(callback){
callback(null, 'param1');//the first parameter is the error - if there is one
},
function(param2, callback){
callback(null, 'param2');
}
], function(err, result){
// if no errors send response back to angular
})
這樣你就可以不用嵌套調用了。 有關更好的示例,請參閱我提供的鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.