Displaying data from Java backend to Angular front-end using HTTP

I'm in the process of developing an application that utilizes an Angular frontend and Java backend. I am looking to showcase data from the backend, which is stored in JSON format. How can I achieve this?

Initially, I created a JSON array in my Java code, then displayed it on a JSP page (localhost:8080) with the help of a servlet. Subsequently, I made an HTTP GET request in my TypeScript code to fetch the array, followed by displaying the retrieved data using ngFor directive in my HTML.

This is how I created the JSON array in Java:

public static JsonArray displayClients() {
    MongoCollection<Document> collection = MongoMain.getDB().getCollection("Clients");

    FindIterable<Document> iterDoc = collection.find();
    Gson gson = new Gson();
    Iterator<Document> it = iterDoc.iterator();
    JsonArray array = new JsonArray();

    while (it.hasNext()) {
        array.add(gson.toJson(it.next()));
    }
    System.out.println(array);
    return array;
}

As for displaying on the server:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/json");  
    request.setAttribute("someData", Clients.displayClients());
    RequestDispatcher dispatcher = request.getRequestDispatcher("test.dispatcher.forward(request, response);  
}

The TypeScript logic to retrieve data on the frontend:

clients: Clients[] = [];

constructor(private http: HttpClient) { }

ngOnInit() {
    this.http.get<Clients[]>("http://localhost:8080/my-app/test").subscribe(result => {
        this.clients = result;
    }, error => alert("Error"));
}

The following HTML snippet displays the entire array:

<ul class="list-group-item-heading" *ngFor="let client of clients; let i = index">
    {{ client }}
</ul>

Even though I have only one record in my array, I am facing an issue where I cannot display specific fields such as just the name or email using {{ client.email }} in my HTML.

My desired output would be something like (combining name and nickname for example):

test test

Rather than displaying all the available data.

Answer №1

To efficiently troubleshoot and review the results, utilize *ngFor. Simply include the following in your html:

{{ customers | json }}

If you confirm that the JSON data is accurate, proceed to write the code as follows:

{{ customer.name }}

Answer №2

https://jsonexamplelink.com
"{\"timestamp\":1557130609,\"machineIdentifie...."

The snippet above reveals that there are backslashes in your code, indicating it is not correctly structured as JSON.

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

If the parent is optional, types cannot be obtained

I'm trying to set the type ShowOptions as "ALL", "ACTIVE", or "DRAFT" However, I encountered an error saying TS2339: Property show does not exist on type Does anyone have suggestions on how I can extract the ShowOptions ...

Ways to modify the server port beyond 3000?

After completing the Angular 2 tutorial, I encountered an issue with changing the localhost port from 3000 to 8000. I noticed a line in my package.json file that reads "start": "concurrent \"npm run tsc:w\" \"npm run lite\" " which I th ...

Stylish elements within a higher-order component in a React application

Encountering two problems when using styled components within a higher order component wrapper in react. The component is being rendered without the specified background color. Encountering TypeScript errors with the ComponentWithAddedColors. Unable to id ...

Developing a customized ResourceConfig that mimics the default Jetty's Jersey registration process

I am currently working on an endpoint implementation that looks like this: @POST @Path("/test") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String canaryTest(String JSON) { return JSON; } When I integrate this e ...

Issue with Angular 6.1.0: Scroll position restoration feature malfunctioning

RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' }) In the latest version 6.1.0, there is a new feature that aims to restore the scroll position after navigation. Unfortunately, I encountered an issue where the scroll restorat ...

Creating a powerful Master/Detail component using JSON data and incorporating a customizable template and function

Recently, I've delved into the realm of Knockout and for the most part, everything has been smooth sailing. However, there is one issue that has me scratching my head, and I was hoping to find some assistance here. My challenge involves creating a Kno ...

What is the best way to change a single string into a JsonArray on android devices?

Having trouble converting a String[] to a JsonArray in Android development. I need to store call log details in a MySQL database, but unsure how to convert the string data into a JsonArray. Any assistance is greatly appreciated. Thank you! Below is an exc ...

Attempting to retrieve a cost with Selenium in a Java program within a product container

In my current project, I am facing a challenge with Selenium and JAVA. There are six app-item-boxes on the webpage and I need to retrieve the price from the specific app-item-box that matches the name "M4A4 | asiimov (Field-Tested)" with a price of 118.04. ...

"Error in Visual Studio: Identical global identifier found in Typescript code

I'm in the process of setting up a visual studio solution using angular 2. Initially, I'm creating the basic program outlined in this tutorial: https://angular.io/docs/ts/latest/guide/setup.html These are the three TS files that have been genera ...

How can I specify a "router" member variable in Angular?

In Angular 9, I am working on a parent component where I need to pass a function to a child component. Specifically, I want to pass the "onNavigate" function to the child component... import { Router, ActivatedRoute } from '@angular/router'; ... ...

Deactivate digital signature in JAVA service provider for SAML2 request

Currently, I am in the process of integrating a Java SP (service provider) with an existing IDP (.net). My concern is that the service provider is sending the request with < SignedInfo> which is unnecessary for my requirements. Is there a way to tog ...

Test fails in Jest - component creation test result is undefined

I am currently working on writing a Jest test to verify the creation of a component in Angular. However, when I execute the test, it returns undefined with the following message: OrderDetailsDeliveryTabComponent › should create expect(received).toBeTru ...

What makes it still feasible to convert any type of variable to "any" in TypeScript?

As I continue to improve my coding skills with TypeScript, I find myself in the shoes of a full stack developer experienced in C#, an object-oriented programming language. Personally, I have a strong distaste for dynamically typed languages and fortunately ...

The server experiences a spike in RAM usage, leading to a server crash

I recently set up a Minecraft server on a VDS with 4GB RAM and 4 core 1Hz CPU running Ubuntu 16.04 x86_64. However, I've encountered a major issue with the RAM usage. As time passes, the RAM usage keeps increasing even when I am the only player on th ...

"Exploring the process of parsing a JSON array containing multiple objects using JSON in an android

Can anyone help me with parsing multiple objects in JSON? Here is an example of my JSON data: { "result": [ [{ "date": "21.12.2016", "day": "Wednesday", "time": "08:00-09:20", "subject": "Physic ...

What are the steps to unmarshal a JSON file?

Could someone help me with deserializing a JSON file? I have a JSON file with an array containing 3 elements. However, I'm unsure about the structure of the elements - specifically regarding the properties Id, Name, Driver, and the data inside the Dri ...

Turning HTML into PDF using Angular 10

I am having success generating a PDF from my HTML page when the data is bound to td directly from ts. However, I face issues when trying to bind the value to an input. You can see a working example on Stackblitz. Generating a PDF for my ...

Matching Android versions with the Math.toIntExact utility method compatibility

I am encountering an issue where the Math.toIntExact method is causing an exception on my Android 6.0 emulator. (Newer emulator versions do not have this problem) I only came across this Microsoft documentation mentioning the issue. Is it correct to assum ...

Unleash the power of Ionic 3 Calendar by capturing the date change event during selection

When a user selects a date, I need to use that date to perform a search in a database. However, I also need to capture the event when another date is selected in the calendar. Here is my HTML code: <ion-calendar #calendar [events]="currentEvents" ...

Managing parallel test execution with the same browser (Firefox) in WebDriver

WebDriver: What is the best approach for running parallel tests with the same Firefox browser? I'm struggling with sharing cookies between multiple instances of the same browser while executing numerous tests simultaneously. Any solutions for this ...