【问题标题】:Indented $http calls with AngularJS使用 AngularJS 缩进 $http 调用
【发布时间】: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


【解决方案1】:

.then()回调中的对象为响应对象,包含状态、数据等属性。您应该执行以下操作:

$http.post('/api/stations/', station)
.then(function(response) {
    $scope.station = response.data.station;
})

【讨论】:

  • 是的 Fissio。你的建议回答了我的问题。感谢您的帮助。
【解决方案2】:

使用 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);
        });
});

【讨论】:

    【解决方案3】:

    我建议使用async waterfall.

    这是一个示例(在后端):

    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
    })
    

    这样你就可以不用嵌套调用了。有关更好的示例,请参阅我提供的链接。

    【讨论】:

      猜你喜欢
      • 2015-01-02
      • 1970-01-01
      • 2016-07-17
      • 2011-05-20
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      相关资源
      最近更新 更多