Tips for stripping out the $promise and $resolved properties from a JSON object

Utilizing $resource in Angular, I am retrieving a JSON object with the following structure:

[
    {
        "id": 0,
        "name": "Type1"
    },
    {
        "id": 1,
        "name": "Type 2"
    }
]

Upon fetching the data, when I console.log(jsonObject), it displays:

[Resource, Resource, $promise: Object, $resolved: true]

I am seeking a way to eliminate $promise & $resolved from the resulting object. I attempted using angular.fromJson(json), but these properties persist.

Answer №1

In my search for a solution, I have come across an unconventional method that serves its purpose:

Consider creating a function like the one below:

function refineData(data) {
    return JSON.parse(angular.toJson(data));
}

You can then utilize this function in each query as shown here (admittedly not the most elegant approach):

function fetchData() {
    Resource.fetch({}, function (result) {
        $scope.data = refineData(result);
    }, function (error) {
        //handle error
    })
}

I am open to learning a more efficient way of achieving this if anyone is willing to share their knowledge.

Answer №2

Snippet from one of my coding projects

Accessing the shared diaries in Diary app:
Diary.getSharedWithMe(function(data) {
        delete data.$promise;
        delete data.$resolved;
        _self.sharedDiariesWithMe = data;
    }, function(error) {
        console.log(error)
    });

Answer №3

According to the insights provided in this response, it seems that you can easily access yourResource.toJSON().

Answer №4

Dealing with the same issue multiple times led me to always defaulting to using $http instead of $resource. However, today I made a conscious effort to tackle this problem head-on. Hopefully, someone will benefit from this solution in the future.

Once you have retrieved your object containing $promise, simply use angular.copy(data) like this:

someService.fetchData($scope.someId).$promise.then(function (data) {
    if (data) {
        $scope.filteredData = angular.copy(data);
    }
});

Now, observe that your filteredData only includes the necessary objects, with $promise and $resolved no longer present.

Answer №5

Dealing with a similar problem myself. Fortunately, I discovered that by ensuring both angular and angular-resource are the same version, the issue disappeared effortlessly. I trust this advice proves beneficial to you!

Answer №6

In a nutshell: By using the angular.fromJson(angular.toJson(resp)) method, you can strip away any specialized Angular functions and obtain a pristine data object.

Answer №7

Are you utilizing the isArray function or the .query() method in conjunction with your $resource object?

According to the $resource documentation:

isArray – {boolean=} – If true then the returned object for this action is an array.

UPDATE:

If you are properly implementing $resource, here are some options available to you:

1) Have the backend deliver the data within an object, for example, { data: [] } instead of just an array.

2) If that is not feasible, utilize the callback from the $resource.query() method, like so:

MyResource.query({ myParams: 'something'}, function(result) {
    // Perform actions on the result
});

Answer №8

I came up with a quick and reusable method to use angular.toJson (removing properties with leading $$):

yourApp.factory('Service', ['$resource', function ($resource) {
    return $resource('your/rest/api/path');
}]);

 yourApp.factory('commonServices', function () { 
         return {
                toJson : function(response){
                    return JSON.parse(angular.toJson(response));
                     //*or* 
                    //return angular.toJson(response);
                }
    });

You can then implement something like this in your controller:

 yourApp.controller('Controller', ['$scope', 'Service','commonServices',  
function ($scope, Service, commonServices) {
            Service.get().then(function (data) {
                $scope.myData = commonServices.toJson(data);
            });
        });

A simpler way is to directly use angular.toJson within the controller:

 yourApp.controller('Controller', ['$scope', 'Service',  
function ($scope, Service, commonServices) {
            Service.get().then(function (data) {
                $scope.myData = angular.toJson(data);
            });
        });

Answer №9

Here is a simple solution:

jsonObject.$promise = null; jsonObject.$resolved = null;

By setting $promise and $resolved to null instead of undefined, you can have more flexibility in your code.

Answer №10

Why not try implementing a service and controller with similar code like this:

myApp.factory('MyService', ['$http', function ($http) {
    return $http.get('your/api/path');
}]);

Then in your controller, you can do something like this:

myApp.controller('MyController', ['$scope', 'MyService', function ($scope, MyService) {
    MyService.then(function (response) {
        $scope.data = response.data;
    });
});

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

`Troubleshooting Issue: Autocomplete feature in Jquery Codeigniter not functioning

Having an issue with autocomplete in my codeigniter project. When I input text into the field, a dropdown appears but no values are shown. It looks like this: Screenshot The error displayed in the console is: Screenshoot Below is the relevant code: Mode ...

My Angular7 app.component.html file is not displaying the routing. What could be the issue?

After implementing the code in app.component.html in Angular 7 like this: <div id="wrapper"> <header id="header-container" class="fullwidth"> <div id="header"> <div class="container"> <div class="left- ...

Combining arrays in JavaScript to form object values with lodash

In my current project, I am attempting to manipulate JavaScript object arrays using lodash. The goal is to stack array values from different objects and map them to corresponding objects in a new array. Here's an example of what I'm working with: ...

What is the location of the files stored using the cordova-file-plugin?

Currently, I am in the process of developing an Excel application on a mobile device. Initially, I'm testing it out on Android, but the aim is to ensure compatibility with iOS devices as well. To build this app, I referred to the official documentati ...

There seems to be a glitch in the AJAX code

I am currently working on a project that involves displaying categories and subcategories of products on a webpage. When users click on either a category or a subcategory, AJAX is used to send the selected item to a php script which then generates HTML cod ...

"An error is occurring in JavaScript: $ is not defined, but I am uncertain of the reason for it

I am attempting to test a code involving html, css, and javascript but it is not functioning as expected. I am unsure of the reason. click here to view image Create a random name generator with customizable input names and display the winner selected by t ...

iOS Safari 16.5 failing to show permission prompt for Notification.requestPermission() prompt

Recently, I have been working on integrating Firebase Cloud Messaging into an iOS Safari browser due to the support for Push Notification and Notification API. function requestPermission() { console.log("request permission") Notification.r ...

Error: The requested address is currently in use by Node.js and Express

Every time I try to save my files using nodemon, an error pops up with the following message: events.js:292 [0] throw er; // Unhandled 'error' event [0] ^ [0] [0] Error: listen EADDRINUSE: address already in use :::9000 [0] at Se ...

Tips for effectively using the parseInt function to access and verify a span element from inside a chrome extension

Trying to utilize parseInt to ascertain if a span element is greater than or equal to 1 within my Google Chrome Extension. Attempting to monitor this "0" for changes and trigger a specific URL upon change - Refer to the Image View of the "inspect" option ...

Learn the process of transferring information through ajax while managing dependent drop-down menus

I have successfully set the initial value from the first combo-box and now I am looking to send the second variable from the second combo-box and receive it in the same PHP file. Below is the Ajax code snippet: $(document).ready(function(){ $(".rutas") ...

What is the process for handling authorization in RESTful requests using angularjs?

Currently, I am utilizing angularjs to send REST requests to an API that necessitates authorization. The authorization process demands the request to be signed (reminiscent of how Amazon s3 operates), and this signature must be included in the headers. My ...

Tips for sending an API request from a local Ionic server to a separate local Express server

I currently have two applications running on my local machine: an ionic2 app running on http://localhost:8041 and an express app running on http://localhost:8000. Using Angular 2 observables, I am encountering an issue when making API calls with absolute p ...

Updating environment variables in a React app without the need to rebuild the image

As I work on developing a Dockerized React application, I have encountered the challenge of defining environment variables for API URLs. React injects these variables during the build phase, meaning that I have to rebuild the entire image every time the en ...

The inverse function for Ember Handlebars helper options is experiencing an undefined error

With a template in hand, I needed to toggle the display of certain text based on a method's return value. Research led me to the recommendation of using handlebars helpers for this purpose. So, I implemented a resetPassword helper within the controlle ...

Combining Objects in an Array using JavaScript

Here is an array example: let array = [ { yearBirth : 1995, name : 'daniel', }, { yearBirth : 1995, name : 'avi', }, { yearBirth : 1993, name : 'john', }, { yearBirth : 1993, n ...

Using ngTouch for ng-click events on the body element can cause issues with links and input fields on mobile

Seeking assistance with a unique issue I am facing on my app-like website. I have implemented a swipable menu but I want it to close whenever the user taps outside the menu. I have tried using ngTouch for swiping and attached ng-click="menuToggled = false" ...

Trouble updating values in Javascript objects

I'm having trouble understanding a problem I am experiencing. When I receive a Json object as a Websocket message from a hardware device, the property `uiAppMsg` is encoded in base64. After decoding it, I attempt to reassign it to the `uiAppMsg` prop ...

Creating a static view in ng-admin without triggering a backend request

Is there a way to include a static view in ng-admin without needing to make a backend call? I'm looking to add something like an about section. Any suggestions on how to achieve this? ...

Display the contents of a post within the same page using ReactJS

I am currently in the process of setting up a blog. In my index.js file, I have a left sidebar that displays the links to the articles. My goal is to have the post content show up in the right sidebar of the index.js file when I click on a link, instead of ...

Error in Vue: Trying to set a property ('message') on an undefined object

As a newcomer to Vue.js, there are some concepts that I may be overlooking. Despite working on it for months, I have been unable to find a solution. My goal is to change the message displayed in a v-alert by using a separate JavaScript script to import the ...