попытка обновить значение с помощью настраиваемого действия в вызове ресурсов AngularJS $

Я изо всех сил пытался найти хороший способ выполнить операцию ввода с использованием ресурса angularJS $. У меня есть сопоставление, которое вернет массив значений в моем веб-сервисе, а также у меня есть конечные точки POST и PUT для выполнения вставки и обновления. У меня есть запрос на работу, чтобы получить массив значений и отобразить на странице. теперь, когда я пытаюсь отредактировать значение и вызвать пользовательскую опцию «обновление», которая была создана для выполнения операции PUT.

Мой контроллер выглядит так

(function () {
'use strict';

var anErrorOccurred = 'An error has occurred.';
var noRecordsFound = 'No records were found.';

angular
    .module('customerContactInfo')
    .controller('customerContactInfoSearchController', ['$rootScope', '$scope',
        'customerContactInfoService', 'utilities',
        controllerFunc
    ]);


function controllerFunc(rootScope, scope,
    customerContactInfoService, utilities) {
    var self = this;
    this.fetchList = function () {
        customerContactInfoService.query(buildQueryObject(), function (data) {
            if (data.length === 0) {
                setPageMsg('infomsg', noRecordsFound);
            } else {
                setPageData(data, '');
            }
        }, function (response) {
            if (response.status === 404) {
                setPageMsg('errormsg', noRecordsFound);
            } else {
                setPageMsg('errormsg', anErrorOccurred);
            }
        });
    };

    function setPageData(data, message) {
        scope.customerContactInfoList = data;
        scope.error = message;
    }

    function setPageMsg(type, msg) {
        scope[type] = msg;
    }

    function buildQueryObject() {
        console.log(scope.accessToken);
        return {
            accessToken: scope.accessToken || rootScope.globalAngObj.customerSpaToken,
            userId: scope.userId || rootScope.globalAngObj.userId
        };
    }

    function buildQueryObjectForUpdate(customerIdUpdate, customerAddressNewValue) {
        return {
            accessToken: scope.accessToken || rootScope.globalAngObj.customerSpaToken,
            customerId: customerIdUpdate,
            customerMessageAddress: customerAddressNewValue
        };
    }

    function initPage() {
        scope.customerContactInfoList = undefined;
        scope.infomsg = undefined;
        scope.errormsg = undefined;
        scope.sortType = 'customerLastName'; // set the default sort type
        scope.sortReverse = false; // set the default sort order
        scope.searchCustomers = ''; // set the default search/filter term
    }

    function checkChildInit() {
        if (scope.$root.initChildApp) {
            self.fetchList();
        }
    }

    this.editDirectMsgAddress = function (customerContactInfo) {

        var note = customerContactInfoService.query(buildQueryObject());
        // Now call `update` to save the changes on the server
        note.$promise.then(function () {
            customerContactInfoService.$update(buildQueryObject(),
                buildQueryObjectForUpdate(customerContactInfo.customerId,
                    customerContactInfo.customerMessageAddress));
        });
    };

    initPage();
    checkChildInit();
}
})();

Мой сервис выглядит так:

(function () {
'use strict';

angular
    .module('customerContactInfo')
    .factory('customerContactInfoService', ['$resource', 'serviceResolver',
        customerContactInfoServiceFactory
    ]);

function customerContactInfoServiceFactory(resource, serviceResolver) {
    return resource(serviceResolver.customerContactInfoWebservice.endpoints.get +
        '/:userId/?access_token=:accessToken', {}, {
            query: {
                method: 'GET',
                isArray: true,
                timeout: 10000,
                withCredentials: true
            }
        }, {
            update: {
                method: 'PUT'
            }
        });
}
})();

Мой HTML-код выглядит так:

<div class="app-table" ng-show="customerContactInfoList">
    <h5 class="information-text show-msg">Enter the customer messaging address to receive goods alerts for retail.
    </h5>
    <br>
    <div class="alert alert-danger error app-error-msg" role="alert" ng-class="{'show-msg':errormsg}" >{{errormsg}}</div>
    <div class="alert info app-info-msg" role="alert"  ng-class="{'show-msg':info}" >{{info}}</div>
    <div class="input-group">
        <label for="userId">Search Customer</label>
            <input type="text" placeholder="Search for Customer" ng-model="searchCustomers" ng-model-options="{debounce:250}">
    </div>
    <table class="tableone table table-hover">
            <thead>
                <tr>
                    <th class="portlet-table-header tabBtn" ng-click="sortType = 'customerLastName'; sortReverse = !sortReverse">
                        customer Last Name
                          <span ng-show="sortType == 'customerLastName' && !sortReverse"></span>
                          <span ng-show="sortType == 'customerLastName' && sortReverse"></span>
                    </th>
                    <th class="portlet-table-header tabBtn" ng-click="sortType = 'customerFirstName'; sortReverse = !sortReverse">
                        customer First Name
                          <span ng-show="sortType == 'customerFirstName' && !sortReverse"></span>
                          <span ng-show="sortType == 'customerFirstName' && sortReverse"></span>
                    </th>
                    <th class="portlet-table-header tabBtn" ng-click="sortType = 'customerId'; sortReverse = !sortReverse">
                      customer ID
                          <span ng-show="sortType == 'customerId' && !sortReverse"></span>
                          <span ng-show="sortType == 'customerId' && sortReverse"></span>
                    </th>
                    <th class="portlet-table-header tabBtn" ng-click="sortType = 'customerMessageAddress'; sortReverse = !sortReverse">
                        customer Messaging Address
                                <span ng-show="sortType == 'customerMessageAddress' && !sortReverse"></span>
                                <span ng-show="sortType == 'customerMessageAddress' && sortReverse"></span>
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="item in customerContactInfoList | orderBy:sortType:sortReverse | filter:searchCustomers track by item.customerId">
                    <td class="last-name">{{item.customerLastName}}</td>
                    <td class="first-name">{{item.customerFirstName}}</td>
                    <td class="customer-id">{{item.customerId}}</td>
                    <td class="customer-msg-address">
                        <input class="customer-msg-address" size="320" type="text" ng-model=item.customerMessageAddress
                               ng-blur="customerContactInfoSearchController.editDirectMsgAddress(item)">
                      </input>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

Мой URL-адрес получения выглядит так

http://goods.nttf.com/customer-contact-info-ws/data/{userId}

Мой пост и URL-адрес выглядят так

http://goods.nttf.com/customer-contact-info-ws/data/

Он не смог распознать функцию обновления в ресурсе.

appvendor.js:3 TypeError: e.$update не является функцией в scripts.js:1 в i (appvendor.js:3) в appvendor.js:3 в n.$digest (appvendor.js:3) в n .$apply (appvendor.js:3) в g (appvendor.js:2) в r (appvendor.js:2) в XMLHttpRequest.w.onload (appvendor.js:2) «Возможно, необработанный отказ: {}»


person Munny    schedule 16.07.2018    source источник


Ответы (1)


Вы можете объяснить немного больше?

Просто запомните подход с $resource :

var User = $resource('/user/:userId', {userId: '@id'});
User.get({userId: 123}).$promise.then(function(user) {
    user.abc = true;
    user.$save();
});

Методы действия над объектом класса или объектом экземпляра могут быть вызваны со следующими параметрами:

"class" actions without a body: Resource.action([parameters], [success], [error])
"class" actions with a body: Resource.action([parameters], postData, [success], 
[error])
instance actions: instance.$action([parameters], [success], [error])

Я знаю, что это не полное решение, но могу направить вас. https://docs.angularjs.org/api/ngResource/service/$ ресурс

Пожалуйста, дайте мне знать, если я могу помочь вам с дополнительной информацией

person javier muñoz    schedule 16.07.2018
comment
могу ли я использовать запрос вместо получения - person Munny; 17.07.2018