如何在 Angular 中使用 Promise() 显示来自后端的数据?

How to display data from backend with a Promise() in Angular?

我想显示从我的后端到我的 Angular 前端的页面。

后端:在“http://localhost:8080/test”我显示一个简单的 "hello" 文本。

前端:在“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' }); 消息。

谢谢!

您可以访问 API 的承诺响应,如下所示

getData() {
 this.getEditeur().then(res=>{
   //use res as response from api
    this.data = res;
 }).catch(error =>{
   console.log(error);
  });
}

修改于 https://whosebug.com/posts/56560723/revisions

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

组件

  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>

demo

everytime you click the button will act to give nre promise after this promise resolve the data will be render by json pipe that why I add times property

没有异步管道你可以使用async/await

  async getData() {
    this.data = await this.getEditeur();
  }

demo ⚡⚡

终于可以使用promise then方法了

  getData() {
    this.getEditeur().then(result=> this.data = result);
  }

检查这个Promise

我相信使用 Observable.toPromise

可以简化您的 getEditeur 函数
getEditeur() {
   return this.http.get('http://localhost:8080/test').toPromise()
}