【问题标题】:How to display data from backend with a Promise() in Angular?如何在 Angular 中使用 Promise() 显示来自后端的数据?
【发布时间】:2019-10-26 20:14:37
【问题描述】:

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

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

前端:在“http://localhost:4200/editeur”有一个按钮。当我点击按钮时,我想在按钮下显示我的“http://localhost:8080/test”内容(在这种情况下是我的“你好”文本)。

我在 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' }); 消息。

谢谢!

【问题讨论】:

  • 你有什么错误吗?如果是,请发布错误

标签: angular express promise angular-fullstack


【解决方案1】:

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

组件

  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 ??

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

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

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

demo ⚡⚡

终于可以使用promise then方法了

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

检查这个Promise

【讨论】:

  • 谢谢。你用你的第一个选项回答了我的问题,但它只适用于 Json 对象。最终目的是显示在后端显示的不是 Json 对象的对象 - 这是我的后端使用 Node 服务器创建的编辑器。我怎么能显示它?谢谢!
  • 欢迎您提供帮助,我已经更新了异步管道部分和现场演示??
  • 检查 ng-container @Théo.G
【解决方案2】:

我相信您的 getEditeur 函数可以通过使用 Observable.toPromise 来简化

getEditeur() {
   return this.http.get('http://localhost:8080/test').toPromise()
}

【讨论】:

  • 这是正确的方法,应该是正确的答案
【解决方案3】:

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

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

修改自https://stackoverflow.com/posts/56560723/revisions

【讨论】:

  • 你好,你需要把 this.data 移到 then 的正文中
猜你喜欢
  • 1970-01-01
  • 2020-05-25
  • 2019-12-20
  • 2017-11-03
  • 1970-01-01
  • 2018-02-08
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
相关资源
最近更新 更多