Issue: Unable to delete message due to message.$delete not being a valid function

Every time I attempt to execute a DELETE request using the angular-resource service, I consistently encounter the following message within the dev tools:

Error: message.$delete is not a function $scope.deleteMessage@file:///Users/me/Desktop/angular/my-app/loyalty-program_messages-pointstransactions.js:37:13 anonymous/fn@file:///Users/me/Desktop/angular/my-app/angularjs/angular.js line 14605 > Function:2:329 expensiveCheckFn@file:///Users/me/Desktop/angular/my-app/angularjs/angular.js:15694:18 ngEventHandler/https://code.jquery.com/jquery-1.12.4.min.js:3:12392 n.event.add/r.handle@https://code.jquery.com/jquery-1.12.4.min.js:3:9156

I've noticed that there seems to be an absence of angular-resource here. Is there an underlying reason for this?

Here is the module containing the controller:

var myApp = angular.module('myApp', ['ngResource'])

.constant("baseUrl1", MY-TESTING-URL-1)
.config(function($httpProvider) {
    $httpProvider.defaults.withCredentials = true;
})

myApp.controller("MessagesCtrl", function($scope, $http, $resource, baseUrl1){


    $scope.displayMode = "list";
    $scope.currentMessages = null;

    $scope.messagesResource = $resource(MY-TESTING-URL-1 + ":id?projection=full", { id: "@id" });

    $scope.listMessages = function () {
        $scope.foo = $scope.messagesResource.get();

        $scope.foo.$promise.then(function (data) {

            $scope.messages = [];
            for(var i = 0; i < $scope.foo._embedded.messages.length; i++) {
                var obj = $scope.foo._embedded.messages[i];
                $scope.messages.push(obj);
            }
        });
    }

    $scope.deleteMessage = function (message) {
        message.$delete().then(function () {
            $scope.messages.splice($scope.messages.indexOf(message), 1);
        });
        $scope.displayMode = "list";
    }

    $scope.createMessage = function (message) {
        new $scope.messagesResource(message).$save().then(function(newMessage) {
            $scope.messages.push(newMessage);
            $scope.displayMode = "list";
        });
    }

    $scope.updateMessage = function (message) {
        message.$save();
        $scope.displayMode = "list";
    }

    $scope.editOrCreateMessage = function (message) {
        $scope.currentMessage = message ? message : {};
        $scope.displayMode = "edit";
    }

    $scope.saveEdit = function (message) {
        if (angular.isDefined(message.id)) {
            $scope.updateMessage(message);
        } else {
            $scope.createMessage(message);
        }
    }

    $scope.cancelEdit = function () {
        if ($scope.currentMessage && $scope.currentMessage.$get) {
            $scope.currentMessage.$get();
        }
        $scope.currentMessage = {};
        $scope.displayMode = "list";
    }

    $scope.listMessages();
});

This is the view where the ng-click should trigger a DELETE request:

<div ng-repeat="message in messages">
<div class="data-tables read-{{ message.read }}">
    <div class="data-tables-rows">
        <div class="data-tables-toggle" type="button" data-toggle="collapse" data-target="#collapse_disclaimer_data-table_message-center_{{ $index }}" aria-expanded="false" aria-controls="collapse_disclaimer_data-table_message-center_{{ $index }}" title="View Details">
            <label></label>
        </div>
        <div class="data-table-message hidden-xs" type="button" data-toggle="collapse" data-target="#collapse_disclaimer_data-table_message-center_{{ $index }}" aria-expanded="false" aria-controls="collapse_disclaimer_data-table_message-center_{{ $index }}" title="View Details">
            <p style="white-space: nowrap; width: inherit; overflow: hidden;text-overflow: ellipsis;"><b>message</b><br />
            {{ message.message }}
            </p>
        </div>
        <div class="data-table-date" type="button" data-toggle="collapse" data-target="#collapse_disclaimer_data-table_message-center_{{ $index }}" aria-expanded="false" aria-controls="collapse_disclaimer_data-table_message-center_{{ $index }}" title="View Details">
            <p><b>date</b><br />
            <date>{{ message.dateReceived | date }}</date>
            </p>
        </div>
        <div class="data-table-points hidden-xs points-{{ message.metadata }}" type="button" data-toggle="collapse" data-target="#collapse_disclaimer_data-table_message-center_{{ $index }}" aria-expanded="false" aria-controls="collapse_disclaimer_data-table_message-center_{{ $index }}" title="View Details">
                    <p><b>Points</b><br />
                    {{ message.metadata }}</p>
                </div>
        <div class="data-table-delete">
            <button ng-click="deleteMessage(message)">Delete</button>
        </div>
    </div>

    <div class="collapse" id="collapse_disclaimer_data-table_message-center_{{ $index }}">
        <div class="data-tables-rows">
            <div class="data-tables-spacer" style="visibility:hidden;">
                <input id="data-table-icon" type="checkbox" />
                <label for="data-table-icon"></label>
            </div>
            <div class="well">
                <div class="data-table-message">
                    <p><b>Message</b><br />
                    {{ message.message }}</p>
                </div>
                <div class="data-table-points visible-xs">
                    <p><b>Points</b><br />
                    {{ message.metadata }}</p>
                </div>
            </div>
            <div class="data-tables-spacer">
            </div>
        </div>
    </div>
</div>

The message is sourced from CDN-delivered JSON:

{

"_embedded": {
    "messages": 
        {
            "id": 8,
            "message": "You received points",
            "dateReceived": "2016-08-01T00:00:00.000+0000",
            "read": false,
            "metadata": "50"
         }
     }
}

Despite inspecting the object data through Firefox's debugger option 'Selection to watch expression', no anomalies are apparent. Any insights would be greatly appreciated!

Answer №1

Big thanks to Joaozito Polo for helping us crack the code. The variable newMessage represents the latest object sourced from a resource. Check out the revamped listMessages function below:

$scope.listMessages = function () {
        $scope.foo = $scope.messagesResource.get();
        $scope.foo.$promise.then(function (data) {
            $scope.messages = [];
            for(var i = 0; i < $scope.foo._embedded.messages.length; i++) {
                var obj = $scope.foo._embedded.messages[i];
                var freshMessage = new $scope.messagesResource(obj)
            $scope.messages.push(freshMessage);
            }
        });
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looping through data in AngularJS with duplicated entries

I'm having an issue with my AngularJS ng-repeat when trying to display JSON data. The records are duplicating, but only after reloading the page. Initially, everything works fine. Take a look at the JSON data below: [{ "EmployeeName": "Jishn ...

Failed to load TypeScript file or similar issue

Whenever I attempt to generate a TypeScript file from a partial view (MVC .NET) that is loaded through a rest call and then appended to a div element, I encounter an error in my console. The error message reads: Uncaught ReferenceError: xyz is not defined ...

Error: Unable to access the 'style' property of null in prac.js at line 3

const heading = document.querySelector("h1"); heading.style.color = "blue"; Encountering an error when attempting to apply color to h1 element using DOM manipulation within a separate JavaScript file. The 2-line code snippet works flawlessly in the consol ...

Attempting to save data to an external JSON file by utilizing fs and express libraries

I've encountered a challenge while attempting to serialize an object into JSON. Despite my best efforts, I keep encountering an error that has proven to be quite stubborn... Below is the code snippet that's causing the issue: APP.post('/api ...

Image not displaying correctly with Neatshow JS Plugin

I've added neatshow.min.js to my project and I'm following all the instructions in the script. The first step is to hide images with CSS, then show them using the script. Here are my instructions: $(window).ready(function(){ $('img&ap ...

Guide to setting a default child route in react-router and updating the URL as needed

Currently, I am utilizing react-router v3 and have a segment of my routing code as follows: ... <Route path='dashboard' component={Dashboard}> <Route path='overview' component={Overview}/> <Route path='scan&apo ...

Working with JSON structure using Javascript

I successfully transformed an XML file into a JSON format, but now I need to manipulate the data in order to achieve a specific desired structure. Here is the Original format { "machine": "Hassia2", "actual_product_date": "08/24/2017", "holdi ...

What is my strategy for testing a middleware that accepts arguments?

Here is the middleware I am working with: function verifyKeys(expectedKeys: string[], req: Request): boolean{ if (expectedKeys.length !== Object.keys(req.body).length) return false; for (const key of expectedKeys) { if (!(key in req.body)) return ...

Unexpected request detected by AngularJS $httpBackend

Attempting to setup a unit test for an AngularJS controller that utilizes a service making a $http.get call. Despite using $httpBackend.expectGET followed by $httpBackend.flush(), the application is attempting to make GET requests for template HTML resourc ...

Using Three.js to rotate a camera-followed sphere in the scene

Currently, I'm developing a Three.js scene with a toy concept where I aim to track a sphere using a camera [demo]. However, I am facing an issue wherein I can't seem to get the sphere to "roll" without causing the camera to also rotate along with ...

The reducer is failing to import the constants for the action types

The issue I'm facing is with my root reducer that imports action type constants from another file. When the reducer is initially called due to createStore, the values of these constants are undefined. Attempting to convert those constants into functi ...

In what way can a container impact the appearance of a child placed in the default slots?

Visiting the vue playground. The main goal is for the container component to have control over an unspecified number of child components in the default slot. In order to achieve this, it's assumed that each child component must either hold a propert ...

Start the CSS3 animation in reverse right away

I am trying to achieve a "flashing" effect by adding the .shown class to my #overlay, causing the opacity to fade in for 2 seconds and then immediately reverse, fading out for another 2 seconds. After experimenting with removing the class, I found that it ...

Issue with the browser's local storage functionality not functioning as expected

For some reason, I am facing an issue with using browser local storage to store an array. When testing it out, both indexes of the array are returning "null". Can someone help me identify what's going wrong? window.localStorage.clear(); var requester ...

"Implementing form validation and AJAX submission for seamless user interaction

I am seeking a solution to validate my form using ajax and then insert it into the database also utilizing ajax. Although, with the current code, validation messages are displayed, it still performs the insertion. The issue I am encountering seems to be ...

I am unable to submit the form with the sweetalert 2 feature

I've tried numerous solutions, but none seem to work for me. Below is the PHP code I am using: <? if( isset($_POST['btn-login']) ) { $mails = new PHPMailer; $content = "xxxx"; $mails->IsSMTP(); $mails->send(); } ?&g ...

What is the best way to modify or revise meta fields for individual products in order to retrieve multiple images for each product in Shopify?

What is the process for updating or editing meta fields to display multiple images of each product on Shopify? ...

Here are the steps to pass the selected dropdown value to ng-repeat for ordering:

I have a dropdown box with options for filtering data in an ng-repeat by different criteria. How can I pass the selected value from the dropdown to the ng-repeat orderby? Here is my dropdown: <select name='filter_range' id='filter_range ...

Is there a way to block the .load() function directly from the browser console?

I am looking to enhance the user experience on my website by dynamically loading certain content after login. This involves using a $.post(...) method to interact with a servlet that verifies the user's credentials, followed by a $.load(url) function ...

React - Unable to fetch image data in an array

I have created a book list, and everything is functioning well except for the image that I am unable to display. I intend to include the image URL in my list and have it shown. const list = [ { authorName: 'Robin', ...