CRUD服务的更新不适用于构造函数异常

时间:2016-04-18 09:56:14

标签: javascript angularjs

我得到了TypeError: this.service is not a constructor

当我尝试点击保存按钮时,会触发$scope.updateBank,然后Bank.prototype.update方法

inline

控制器中的更新功能

$scope.updateBank = $scope.BankService.update;

创建银行CRUD服务

  

我也试过.service,它仍然不起作用。

angular.module('bank', [])
    .factory('bankService', function($resource, $http) { // I also tried .service, it still not works.
        var Bank;
        return Bank = (function() {
            function Bank(BankListId, errorHandler) {
                var defaults;
                // http://dev.co
                this.service = $resource('/api/v1/banks/:id', {
                    id: '@id'
                }, {
                    update: {
                        method: 'PUT'
                    }
                });
                this.errorHandler = errorHandler;
            }

        Bank.prototype.update = function(bank, bank_id) {
            console.log(bank) // Object {name: "Simonis Inc!!"}
            console.log(bank_id) // 101
            return new this.service({
                Bank: bank
            }).$update({
                id: bank_id
            }, (function() {
                return null;
            }), this.errorHandler);
        };

        // the query all function works perfectly.

        Bank.prototype.all = function() {
            return this.service.query((function() {
                return null;
            }), this.errorHandler).$promise;
        };

更新

banks_controller

$q.all([this.BankService.all().$promise]).then(function(ret){
  $scope.banks = ret[0]
  console.log($scope.banks)
});

$scope.updateBank = this.BankService.update;

REST服务

        Bank.prototype.update = function(bank, bank_id) {
            # here, `this` is the banks_controller
        };

        // the query all function works perfectly.

        Bank.prototype.all = function() {
            # `this` is the Bank
        };

1 个答案:

答案 0 :(得分:2)

错误在于:

$scope.updateBank = this.BankService.update;

永远不要将方法(=与此对象)绑定到另一个对象或“此对象”。将是未定义或指向另一个对象(如$ scope)。

$scope.updateBank = function(){
    this.bankService.update();
}