I'm creating an application with Angular frontend and Java backend and i want to display data from the backend (json), how can i do?

I created an arrayjson in my Java code, then i'm displaying the array on a JSP page (on localhost8080) with a servlet. Then i'm doing an http get in my typescript to get the array, finally i'm displaying the data with a ngfor in my html.

Java creating json array :

public static JsonArray afficherClients() {
    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;
}

Displaying on the server :

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

The typescript in the front end to get data :

clients: Clients[] = [];

constructor(private http: HttpClient) { }

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

The HTML who's showing the entire array :

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

I can have this kind of result with my code :

{\"timestamp\":1557130609,\"machineIdentifier\":11848616,\"processIdentifier\":5812,\"counter\":8628551},\"nomEntreprise\":\"test\",\"rue\":\"test\",\"codePostal\":\"test\",\"ville\":\"test\",\"titre\":\"test\",\"nom\":\"test\",\"prenom\":\"test\",\"telephone\":\"test\",\"email\":\"test\"}"]

I created only 1 record in my array.

But i want to show only the name, or only the email, like {{client.email}} in my HTML but its not working.

So i expect something like (name + nickname for this example) :

test test

And not all of the data.

1 Answers

0
Community On

You can easily debug, check the output with using *ngFor. just add in html:

{{ clients | json }}

If you find the json is comming correct you can then write code as:

{{ client.name }}