【问题标题】:How to display some data in front Angular from Java backend with http如何使用http从Java后端在Angular前面显示一些数据
【发布时间】:2019-09-30 10:31:24
【问题描述】:

我正在使用 Angular 前端和 Java 后端创建一个应用程序,我想显示来自后端 (json) 的数据,我该怎么做?

我在我的 Java 代码中创建了一个 arrayjson,然后我在一个带有 servlet 的 JSP 页面(在 localhost8080 上)上显示了该数组。然后我在我的 typescript 中执行 http get 来获取数组,最后我在我的 html 中使用 ngfor 显示数据。

Java 创建 json 数组:

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;
}

在服务器上显示:

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);  
}

前端获取数据的打字稿:

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"));
}

显示整个数组的 HTML:

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

我的代码可以得到这样的结果:

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

我只在我的数组中创建了 1 条记录。

但我只想在我的 HTML 中显示名称或电子邮件,例如 {{client.email}},但它不起作用。

所以我期望类似(本示例的名称 + 昵称):

测试测试

并不是所有的数据。

【问题讨论】:

  • 你好。你说client.email 不起作用。你能显示错误信息吗?
  • 您好,问题是我在控制台中没有任何显示并且没有错误消息
  • 但是您显示的json不包含name字段
  • 是的,对不起,我翻译了它,使用 client.nom 无论如何它都不起作用
  • 您是否查看了浏览器控制台(对于 google chrome,它是 F12 按钮打开)?

标签: java json angular typescript http-get


【解决方案1】:

您可以使用 *ngFor 轻松调试、检查输出。只需在 html 中添加:

{{ 客户 | json }}

如果你发现 json 是正确的,你可以编写如下代码:

{{ 客户名称 }}

【讨论】:

  • {{ 客户 | json }} 有效,但我不能使用 {{ clients.something }},我没有任何显示
【解决方案2】:
https://json.org/example.html
"{\"timestamp\":1557130609,\"machineIdentifie...."

如上面的摘录所示,您的代码有斜线。它的 JSON 格式不正确。

【讨论】:

    猜你喜欢
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2018-01-27
    • 2021-10-10
    • 1970-01-01
    • 2019-10-26
    相关资源
    最近更新 更多