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

Thé*_*o.G 1 promise express angular-fullstack 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();
});
Run Code Online (Sandbox Code Playgroud)

这是我的 HTML 前端:

<button class="btn btn-success" (click)="getEditeur()">Display backend</button>
Run Code Online (Sandbox Code Playgroud)

这是我的 TS Angular 前端:

getEditeur() {

return new Promise((resolve, reject) => {
  this.http.get('http://localhost:8080/test').subscribe(
    (response) => {
      resolve(response);
    },
    (error) => {
      reject(error);
    }
  );
});
}
Run Code Online (Sandbox Code Playgroud)

当我单击按钮时,console.log('Hello'); 从我的后端工作来看,前端和后端是紧密相连的。但现在我希望我的 Promise() 在屏幕上显示该res.json({ message: 'Hello' });消息。

谢谢 !

mal*_*awi 5

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

\n\n

成分

\n\n
  data = null\n  i = 1;\n\n  getEditeur() {\n\n    return new Promise((resolve, reject) => {\n      // call the api => \n      // get the result ... \n      resolve({ message: \'Hello\', times: this.i++ });\n    });\n  }\n\n  getData() {\n    this.data = this.getEditeur();\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

模板

\n\n
<button (click)="getData()">Click</button>\n\n<pre>\n  {{data | async | json}}\n</pre>\n\n<ng-container *ngIf="data | async  as messageData">\n  <div>message from server {{messageData.message}} , times {{messageData.times}}</div>\n</ng-container>\n
Run Code Online (Sandbox Code Playgroud)\n\n

演示

\n\n
\n

每次您单击按钮时,都会给出 nre 承诺,在此承诺解决后,数据将通过 json 管道呈现,这就是我添加 times 属性的原因

\n
\n\n

如果没有异步管道,您可以使用async/await

\n\n
  async getData() {\n    this.data = await this.getEditeur();\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

演示 \xe2\x9a\xa1\xe2\x9a\xa1

\n\n

最后你可以使用 Promise then 方法

\n\n
  getData() {\n    this.getEditeur().then(result=> this.data = result);\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

检查这个承诺

\n