【问题标题】:Angular, how to check if Post is done. ToPromise() and subscribe() not workingAngular,如何检查 Post 是否完成。 ToPromise() 和 subscribe() 不起作用
【发布时间】:2021-07-28 21:53:59
【问题描述】:

我不知道为什么(这是我第一次尝试),但即使我的发布请求正在工作,我也无法在完成后打印任何内容。

在 TS 文件中,这是我的代码:

this.appService.sendPath({ title: serviceToPath }).toPromise().then
(
  ()=>
  {
    console.log("The path is set!")
  }
);

那么这就是“appService”我的中间人

sendPath(path: any): Observable<any> {
   console.log("path from app-service: "+ JSON.stringify(path))
   return this.httpClient.post('http://localhost:3000/compare',path)
}

当然是控制台消息“路径已设置!”当“来自应用服务的路径”完美运行时,从不显示在控制台上。

最终目标是在 POST 完成后调用一个函数,但现在,我只想在控制台上打印一些东西。

感谢您的帮助。

更新: 这似乎是因为我的 Post 请求处于永远挂起状态。我该如何解决这个问题?

【问题讨论】:

  • 代码看起来正确。你确定执行丰富的代码调用this.appService.sendPath
  • 远程toPromise(),使用.subscribe并传递错误处理程序以检查是否发生任何错误:this.appService.sendPath({ title: serviceToPath }).subscribe(() =&gt; console.log('The path is set!'), (error: any) =&gt; console.log('Error setting path:', error));
  • @IAfanasov 这就是为什么确实如此奇怪。是的,它被执行是因为“应用服务的路径:”得到正确显示。
  • @MichaelD 我刚刚尝试了订阅 + 错误但没有弹出错误:this.appService.sendPath({ title: serviceToPath }).subscribe( res=&gt; { console.log("The path is set!") }, error =&gt; { console.log("Sending is wrong " + error) } );
  • 非常感谢@IAfanasov 的帮助,非常感谢 :)

标签: angular post promise


【解决方案1】:

为什么不直接订阅你的函数呢?

this.appService.sendPath({ title: serviceToPath })
.subscribe(res => {
  console.log("The path is set!")
});

【讨论】:

  • 我试过了,但那个似乎不起作用。难道是我必须在我的模块中导入一些奇怪的东西?
  • 您是否看到“网络”选项卡中的 POST 请求执行?
  • 不幸的是,我是新手。虽然我确实看到了一些东西(其中一些待定),包括一些预检的东西进入正确的路线,正如我所说的帖子本身正在发布(这些路径导致图像正确显示)所以我不明白为什么不工作.
【解决方案2】:

确实是服务器端出错了。再次感谢 Iafanasov,他给了我一个相当大的线索!

//If you forget this the promise will not work and you will never know when POST is over
res.status(205).send('');

我没有发送状态,所以前端承诺不知道什么时候结束。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 2021-01-07
    • 2017-11-13
    相关资源
    最近更新 更多