首页 > 解决方案 > 如何在 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' });消息。

谢谢 !

标签: angularexpresspromiseangular-fullstack

解决方案


你可以使用异步管道,检查这个例子

零件

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

检查这个承诺


推荐阅读