如何在 angularjs 中删除请求对象中的文件

How do I delete fileds in request object in angularjs

本文关键字:对象 文件 请求 删除 angularjs      更新时间:2023-09-26

我从angularjs控制器向服务器发出请求以获取对象,并且我想在视图显示之前删除对象中的一个字段。Folloiwng 是我的代码

$scope.findOne = function() {
    $scope.order = Orders.get({
        orderId: $stateParams.orderId
    });
    delete $scope.order._id;
    console.log(JSON.stringify($scope.order));
};

它打印

{"$promise":{},"$resolved":false}

它不会删除 ID 字段。我的视图甚至显示了我的对象的_id。如何删除该字段?

以下是我的服务文件

"使用严格";

//Orders service used for communicating with the orders REST endpoints
angular.module('orders').factory('Orders', ['$resource',
    function($resource) {
        return $resource('orders/:orderId', {
            orderId: '@_id'
        }, {
            update: {
                method: 'PUT'
            }
        });
    }
]);

当我将 findOne() 更改为

$scope.findOne = function() {
    Orders.get({
        orderId: $stateParams.orderId
        }).success(function(res)//(this is line number 56)
        {
            delete res.data._id;
            $scope.order = res.data;
    });
};

我在控制台中收到此错误

 TypeError: undefined is not a function
    at Scope.$scope.findOne (http://localhost:3000/modules/orders/controllers/orders.client.controller.js:56:14)
    at http://localhost:3000/lib/angular/angular.js:10903:21
    at Scope.$eval (http://localhost:3000/lib/angular/angular.js:12811:28)
    at pre (http://localhost:3000/lib/angular/angular.js:20125:15)
    at nodeLinkFn (http://localhost:3000/lib/angular/angular.js:6732:13)
    at compositeLinkFn (http://localhost:3000/lib/angular/angular.js:6146:13)
    at publicLinkFn (http://localhost:3000/lib/angular/angular.js:6042:30)
    at http://localhost:3000/lib/angular-ui-router/release/angular-ui-router.js:3905:9
    at nodeLinkFn (http://localhost:3000/lib/angular/angular.js:6752:13)
    at compositeLinkFn (http://localhost:3000/lib/angular/angular.js:6146:13) <section data-ng-controller="OrdersController" data-ng-init="findOne()" class="ng-scope">angular.js:10126 (anonymous function)
get默认

返回一个promise对象。这样做的方法是

$scope.findOne = function() {
    Orders.get({
        orderId: $stateParams.orderId
        }).success(function(res)
        {
            delete res.data._id;
            $scope.order = res.data;
    });
};

我将函数更改为

    $scope.findOne = function() {
        var order = Orders.get({
            orderId: $stateParams.orderId
        }, function()
        {
            order.order_type = 'new';
        });
         $scope.order = order;
    };

它奏效了。我想知道语法是否在 angularjs 更新中更改。https://docs.angularjs.org/api/ngResource/service/$resource 中提到了类似的语法。虽然我无法弄清楚其他成功回调答案不起作用的原因.

Orders.get 函数返回一个承诺,记住这一点,你的代码应该看起来像这样:

Orders.get({orderId: $stateParams.orderId}).then(function(order) {
  delete order._id;
  $scope.order = order;
});