Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service is not returning the data

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?

like image 627
change need Avatar asked Nov 22 '25 12:11

change need


2 Answers

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.

like image 189
Antoniossss Avatar answered Nov 25 '25 04:11

Antoniossss


It should be:

return this.http.get('country').subscribe { .......}
like image 42
sabrine abdelkebir Avatar answered Nov 25 '25 02:11

sabrine abdelkebir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!