Utilizing Angular JS and Spring framework to efficiently filter a JSON Object

When attempting to transfer a JSON Object from the Frontend to the Backend through Angular JS and Java Spring using the JHipster Framework, I encountered an issue. The initial JSON Object structure is as follows:

{
"anzahl": 0,
"category": 0,
"id": 0,
"parkraumId": 0,
"timestamp": "2016-09-07T12:59:04.290Z",
"wochentag": 0
}

However, in order to store it in the database using the Spring Repository method createCrowdsource(crowdsource), I needed to filter out the values wochentag and anzahl. This resulted in the revised JSON Object as shown below:

{
"category": 0,
"id": 0,
"parkraumId": 0,
"timestamp": "2016-09-07T12:59:04.290Z"
}

My attempt to achieve this involved specifying the

fields: 'category', 'id', 'parkraumId', 'timestamp'
in the Angular JS controller below. However, when passing this parameter back to the Spring Resource using @RequestParam String fields, the process did not work as expected.

Angular Controller:

function save() {
            vm.isSaving = true;
            if (vm.crowdsource.id !== null) {
                //JSON needs these two attributes

                console.log('Updating!')
                Crowdsource.update(vm.crowdsource, onSaveSuccess, onSaveError, {fields: 'category', 'id', 'parkraumId', 'timestamp'});
            } else {

                Crowdsource.save(vm.crowdsource, onSaveSuccess, onSaveError);
            }
        }

save()

Angular Service:

(function () {
    'use strict';
    angular
        .module('bahnApp')
        .factory('Crowdsource', Crowdsource);

    Crowdsource.$inject = ['$resource', 'DateUtils'];

    function Crowdsource($resource, DateUtils) {
        var resourceUrl = 'api/crowdsources/:siteId';

        return $resource(resourceUrl, {}, {
            'query': {method: 'GET', isArray: true},
            'get': {
                method: 'GET',
                transformResponse: function (data) {
                    if (data) {
                        data = angular.fromJson(data);
                        data.timestamp = DateUtils.convertDateTimeFromServer(data.timestamp);
                    }
                    return data;
                }
            },
            'update': {
                method: 'PUT',

            }
        });
    }


})();

Spring Resource:

/**
 * PUT  /crowdsources : Updates an existing crowdsource.
 *
 * @param crowdsource the crowdsource to update
 * @return the ResponseEntity with status 200 (OK) and with body the updated crowdsource,
 * or with status 400 (Bad Request) if the crowdsource is not valid,
 * or with status 500 (Internal Server Error) if the crowdsource couldnt be updated
 * @throws URISyntaxException if the Location URI syntax is incorrect
 */
@RequestMapping(value = "/crowdsources",
    method = RequestMethod.PUT,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Crowdsource> updateCrowdsource(@RequestParam String fields, @RequestBody Crowdsource crowdsource) throws URISyntaxException {
    log.debug("REST request to update Crowdsource : {}", crowdsource);
    log.debug(crowdsource.toString());
    if (crowdsource.getId() == null) {

        return createCrowdsource(crowdsource);
    }
    Crowdsource result = crowdsourceRepository.save(crowdsource);
    crowdsourceSearchRepository.save(result);
    return ResponseEntity.ok()
        .headers(HeaderUtil.createEntityUpdateAlert("crowdsource", crowdsource.getId().toString()))
        .body(result);
}

Crowdsource:

/**
 * A Crowdsource.
 */
@Entity
@Table(name = "crowdsource")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "crowdsource")
@JsonFilter("myFilter")
public class Crowdsource implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "category")
    private Integer category;

    @Column(name = "timestamp")
    private ZonedDateTime timestamp;

    @Column(name = "parkraum_id")
    private Integer parkraumId;


    private Integer anzahl;

    private Integer wochentag;


    public Integer getAnzahl() {
        return anzahl;
    }

    public void setAnzahl(Integer anzahl) {
        this.anzahl = anzahl;
    }

    public Integer getWochentag() {
        return wochentag;
    }

    public void setWochentag(Integer wochentag) {
        this.wochentag = wochentag;
    }

    // More methods...

}

Answer №1

In order to prevent the values from being saved permanently, you can mark them with the @javax.persistence.Transient annotation in the CrowdSource class. This will prevent them from being saved in the database.

@Transient
private Integer quantity;

@Transient
private Integer weekday;

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

Adding JavaScript files into Templates or HTML using webpack

Imagine having a server (like Node & Express) that serves HTML pages to clients using template files (such as pug, ejs, handlebars, twig, marko, etc.). It's a typical multi-page website setup where each page has its own JavaScript files. Can webpa ...

passing two $index values in a nested ng-repeat loop

Currently, I have implemented an ng-repeat within another ng-repeat to create a navigation menu. In each <li> element in the inner ng-repeat loop, I have set an ng-click event that triggers the relevant controller for that specific menu item, passing ...

React - The prop value remains static even after the parent component updates its related state

My Application consists of two main components: Button and Input https://i.sstatic.net/9cfCu.png Upon clicking the Click to update state button, the input value initially set as May should be updated to May New. However, I noticed that this change is not ...

The server is receiving empty values from the Ajax post

I'm attempting to extract an image file from a base64 string received from the client side. Here is the ajax post I'm using: $.ajax({type: "POST", url: "upload_post.php", data: postData, dataType: "text", success: function(result){ ale ...

What is the Next.js equivalent of routing with rendering capability for nested component paths?

I am new to Next.js and so far have been loving the experience. I'm a bit stuck on how to achieve the equivalent of the following code in Next.js These are all client-side routes that render nested components on the user page. The value of ${currentP ...

Dropdown box not displaying any choices

I developed a basic reusable component in the following way: Typescript (TS) import {Component, Input, OnInit} from '@angular/core'; import {FormControl} from '@angular/forms'; @Component({ selector: 'app-select', templa ...

What is the best way to submit a dynamically created form within an Angular application?

Hey there! I'm working with a dynamically created form and I need to figure out how to send the form when it's submitted. Any ideas on how to do this would be greatly appreciated! Check out my code on Plunker: Link <form name="MCommForm{{ite ...

Saving maps on React Native can be done easily using AsyncStorage

I am facing an issue with saving user inputs as a JS map using AsyncStorage in my React Native app. Despite no errors during the saving process, I encountered "[object Map]" when attempting to retrieve the data. Here is a simplified version of my user map ...

The one-click button is functional on larger screens, while on mobile devices, only a double click will register

I am facing an issue in angular where a button works perfectly fine with one click on larger screens, such as Macbook. However, on iPhone, it requires a double click to function properly (it works fine on Android too). The alert triggers with a single cl ...

Retrieve an array of information from a firestore database query

I am encountering an issue while trying to retrieve information about all users who are friends of a specific user. I have attempted to gather the data by pushing it to an array and then returning it as a single JSON array. However, it seems that the dat ...

Is it possible for Vue js to display an image from the /dist/ directory even if it is not present?

Currently, I am in the process of learning Vue.js + webpack and have started a project by following these steps: f:www\> npm install -g vue-cli f:www\> vue init webpack-simple my-project f:www\> cd my-project f:www\> npm in ...

Having difficulty adjusting the width of a div element

I've been struggling to adjust the width of the div assigned with the colors class, whether in percentage or pixels. var colors = ["RED", "GREEN", "BLUE", "YELLOW", "PURPLE"]; for (var h = 0; h <= 4; h++) { for (var i = 0; i <= colors.lengt ...

The JSON array provides the ideal syntax for looping purposes

I am working with JSON data and trying to check if a hovered element matches the names 'sports' or 'technology'. If there is a match, I want to retrieve the corresponding 'text' and 'image' values. However, I am only ...

Developing asynchronous DOM functions for optimal performance

Imagine having a large amount of data that needs to be processed. In this scenario, the processing must happen on the client side rather than the server side. The data processing involves iterating through each element in the data set: for element in data ...

How many files are being monitored by Grunt?

Recently, I received a new project using Angular + Node from a client and successfully set it up on my local machine. However, one major issue arose when running the grunt command - my CPU spiked to 100% causing my system to hang. Strangely, the same proje ...

JavaScript code to verify if a checkbox is selected

Having some trouble making a text box value change based on checkbox status. I've attached a function to the onclick event of the checkbox, but it's not quite working as expected. <div> MyCheckbox <input type="checkbox" id="Check1" name ...

Is it possible to utilize a method defined in the controller, such as $rootscope.method(), within a factory?

How do I call the controller method from within a factory? //controller.js $rootScope.stackTraceReport = function(error){ var exception = errorHandler(error); //reporting to server StackTrace.report(exce ...

Sending a Django form using AJAX and jQuery: A step-by-step guide

After researching various tutorials on django AJAX forms, I've found that each one offers a different method, but none of them seem simple. Being new to AJAX, I'm feeling a bit confused by the complexity involved. In my specific case, I have a m ...

Issue with inputting email into Google login popup using Java and Selenium

`Setting the system property for webdriver and initializing a ChromeDriver instance: System.setProperty("webdriver.chrome.driver","C://selinium jar driver//driver/chromedriver.exe"); WebDriver driver = new ChromeDriver(); Accessing a specific URL: driver. ...

The tooltip in nvd3 is displaying the index instead of the label

I'm encountering an NVD3 tooltip issue with my multichart (multiline chart). The XAxis labels are set as JAN, FEB, MAR... DEC. However, when I hover over the graph, it displays 0, 1, 2, 3... 11 as the tooltip title instead of the month names. Here is ...