I have a service with a method like below:
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();
});
}
In similar way I have function in component like below:
public users: any
countCountry() {
this.count=this.user.getTotalCountries();
console.log(this.count) //it is not returning any data;
}
I'm not able to figure out why it is not returning data in component.ts. Could anyone please help me?
It is not returning anything because there is no return statement.
It should be
getTotalCountries(){
return this.http.get("country");
}
and later on somewhere in the code, when you subscribe you will make actual request happen
this.user.getTotalCountries().subscribe(val=>this.count=val));
You must be aware that here you have to deal with async code, so that is something that happens out of order.
When you subscribe application continues and actual http call is made in the background. When request finishes, callback is invoked - and that is the code you provide as argument to subscribe.
It should be:
return this.http.get('country').subscribe { .......}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With