angular - 如何在 Angular 中使用 Promise() 显示来自后端的数据?
问题描述
我想显示一个从我的后端到我的 Angular 前端的页面。
后端:在' http://localhost:8080/test '我显示一个简单的“你好”文本。
前端:在“ http://localhost:4200/editeur ”有一个按钮。当我点击按钮时,我想在按钮下显示我的“ http://localhost:8080/test ”内容(在这种情况下是我的“hello”文本)。
我在 Angular 中使用了 Promise()。
这是我的 Express 后端中间件:
server.use('/test', (req, res, next) => {
res.json({ message: 'Hello' });
console.log('Hello');
next();
});
这是我的 HTML 前端:
<button class="btn btn-success" (click)="getEditeur()">Display backend</button>
这是我的 TS Angular 前端:
getEditeur() {
return new Promise((resolve, reject) => {
this.http.get('http://localhost:8080/test').subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
}
当我单击按钮时,console.log('Hello'); 从我的后端作品来看,所以前端和后端连接得很好。但现在我希望我的 Promise() 在屏幕上显示res.json({ message: 'Hello' });
消息。
谢谢 !
解决方案
你可以使用异步管道,检查这个例子
零件
data = null
i = 1;
getEditeur() {
return new Promise((resolve, reject) => {
// call the api =>
// get the result ...
resolve({ message: 'Hello', times: this.i++ });
});
}
getData() {
this.data = this.getEditeur();
}
模板
<button (click)="getData()">Click</button>
<pre>
{{data | async | json}}
</pre>
<ng-container *ngIf="data | async as messageData">
<div>message from server {{messageData.message}} , times {{messageData.times}}</div>
</ng-container>
每次您单击该按钮时,都会在此承诺解决后给予 nre 承诺,数据将由 json 管道呈现,这就是我添加 times 属性的原因
如果没有异步管道,您可以使用async/await
async getData() {
this.data = await this.getEditeur();
}
最后你可以使用 promise then 方法
getData() {
this.getEditeur().then(result=> this.data = result);
}
检查这个承诺
推荐阅读
- javascript - JavaScript“新日期”创建时间与原始日期字符串不同的日期
- c++ - 在 Kubuntu 18.10 上链接的 Vulkan SDK 版本 1.1.85.0
- json - 我正在尝试测试 Apple Push Notification 服务远程通知,但出现错误
- python - 用 pandas 提取一些行
- git - 使用 git rebase 将提交移动到新分支
- python - Python:带有日期时间索引的熊猫分类系列在尝试更改值时中断(ValueError)
- spring - 如何在带有xml的post请求中将请求参数传递给resttemplate - 正文?
- java - 使用 Spring、MyBatis 和 OracleDB 在 Java 中使用多个应用程序服务器进行数据库事务
- sql-server - SQL Server 2016 导入向导 - 尾随空格
- javascript - 如果文本已经输入,JavaScript 不会复制 innerHTML