我有一种服务,其方法如下:
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");
}
然后在代码中的某个地方,当您subscribe
发出实际请求时
this.user.getTotalCountries().subscribe(val=>this.count=val));
您必须意识到,在这里您必须处理异步代码,因此这是乱序的。
当您的subscribe
应用程序继续运行并且在后台进行实际的http调用时。请求完成后,将调用回调-这是您提供的代码作为参数subscribe
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句