保存对angularjs中对象的响应

时间:2015-09-14 12:00:13

标签: javascript angularjs asp.net-mvc

我的页面包含表格,数据通过ng-repeat和ng-model显示。当我单击保存按钮时,我调用post服务并将我的数据发布到db并在回调中返回id。如何保存对象的响应?

控制器中的

$scope.saveTask = function (workflow) {
    if (workflow.isSaved == false) {
        workflow.isSaved = true;
        $scope.Task.push($scope.newTask());
        restService.postArbitraryTask(angular.toJson(workflow));
    }
};

在休息服务中:

postArbitraryTask: function (model, callback) {
    $http({
        method: 'POST',
        url: Global.api.saveArbitraryTask,
        contentType: 'application/json; charset=utf-8',
        data: model
    }).success(function (response) {
        console.log(response);
        if (callback) {
            callback(response);
        }
    }).error(function() {});
},

2 个答案:

答案 0 :(得分:1)

postArbitraryTask函数接受将传递响应的回调。

使用它:

restService.postArbitraryTask(
    angular.toJson(workflow),
    function(response){
        $scope.myObject = response;
    }
);

此外,而不是:

if (workflow.isSaved == false) {

您可以使用:

if (!workflow.isSaved) {

这表现基本相同。

答案 1 :(得分:1)

您的postArbitraryTask接受回调并将回复传递给它

postArbitraryTask: function (model, callback) {
    $http({
        method: 'POST',
        url: Global.api.saveArbitraryTask,
        contentType: 'application/json; charset=utf-8',
        data: model
    }).success(function (response) {
        console.log(response);
        if (callback) {
            callback(response);
        }
    }).error(function() {});
},

您可以修改saveTask函数以使用从服务器返回的任何数据。

$scope.saveTask = function (workflow) {
    if (workflow.isSaved == false) {
        $scope.Task.push($scope.newTask());
        restService.postArbitraryTask(angular.toJson(workflow),
           function(response){
              workflow.isSaved = true;
              workflow.id = response.id;
           }
        );
    }
};

您可以进一步修改代码以处理错误(也不赞成成功和错误):

postArbitraryTask: function (model, callback) {
    $http({
        method: 'POST',
        url: Global.api.saveArbitraryTask,
        contentType: 'application/json; charset=utf-8',
        data: model
    }).then(function (response) {
        console.log(response);
        if (callback) {
            callback(false,response);
        }
    },function(response) {
        callback(true,response);
    });
},

修改你的回调以接受错误

$scope.saveTask = function (workflow) {
    if (workflow.isSaved == false) {
        $scope.Task.push($scope.newTask());
        restService.postArbitraryTask(angular.toJson(workflow),
           function(error,response){
              if(!error){ 
                  workflow.isSaved = true;
                  workflow.id = response.data.id;
              }
              else{
                  //handle error here(display an alert?) if an error occurs or server responds with an error code such as 404 or 500
              }
           }
        );
    }
};