【问题标题】:Angular HTTP get request is not working in ngOnInitAngular HTTP 获取请求在 ngOnInit 中不起作用
【发布时间】:2020-10-16 21:46:29
【问题描述】:

我正在尝试在组件加载时从后端 API 获取数据。

服务文件中的 API 调用

  getFiles(): Observable<any> {
    return this.httpClient.get<any>('http://localhost:5000/api/file');
  }

OnInit内的组件中订阅该服务

  ngOnInit(): void {
    this.postDataService.getFiles().subscribe( data => {
      console.log('test', data);
    });
  }

它给出以下响应(200)。我没有收到任何错误

code: "EINVALIDSTATE"
message: "Requests can only be made in the LoggedIn state, not the SentClientRequest state"

如果我在 (click) 上调用相同的服务,它可以正常工作。

 testClick(): void {
    this.postDataService.getFiles().subscribe( data => {
      console.log('test', data);
    });
  }

ngOnInit 中调用服务是否有任何问题。如何让它发挥作用?


编辑


经过这么多故障排除后,我发现当我尝试直接加载子路由时出现错误。如果我加载主页然后单击链接以导航到任何组件,那么此 api 调用工作正常。

【问题讨论】:

  • 你试过OnChages吗?
  • @Rohith 是的,我做到了。但没有运气
  • ngOnInit 中的请求可能在服务器处于SentClientRequest 状态时发送,而testClick 中的请求在服务器处于LoggedIn 状态时发送。在发送请求之前,您必须等待服务器处于LoggedIn 状态。有没有办法让您在客户端跟踪 loggedIn 状态?
  • @fridoo 经过这么多调试后,我发现当我尝试直接加载子路由时它会出错。如果我加载主页,然后单击链接导航到该组件,那么此调用工作正常
  • @fridoo 是的。我不是很理解。如果我在 app.componet.ts 中调用相同的 api ,它工作正常。

标签: angular httpclient


【解决方案1】:

顺便说一句请求只能在 LoggedIn 状态下发出,而不是 SentClientRequest 状态它不是角度错误。这是服务器端错误

请关注tediousjs.github.io

【讨论】:

  • 是的,我知道。但它适用于点击所以混乱
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多