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.