{ cons-6ren">
gpt4 book ai didi

angular - 服务不返回数据

转载 作者:行者123 更新时间:2023-12-02 20:16:03 27 4
gpt4 key购买 nike

我有一个服务,方法如下:

getTotalCountries() {
this.http.get("country").subscribe((response) => {
console.log(response.json());//it is displaying all the data which is return by API
return response.json();
});
}

以类似的方式,我在组件中有如下功能:

public users: any

countCountry() {
this.count=this.user.getTotalCountries();
console.log(this.count) //it is not returning any data;
}

我无法弄清楚为什么它没有在 component.ts 中返回数据。谁能帮帮我?

最佳答案

它没有返回任何东西,因为没有 return 语句。

应该是

getTotalCountries(){
return this.http.get("country");
}

稍后在代码中的某处,当您订阅时,您将进行实际请求

this.user.getTotalCountries().subscribe(val=>this.count=val));

您必须意识到,在这里您必须处理异步代码,所以这是乱序发生的事情。

当您订阅 时,应用程序继续运行,并在后台进行实际的 http 调用。当请求完成时,将调用回调 - 这是您作为参数提供给 subscribe 的代码。

关于angular - 服务不返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52366000/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com