0

In my service I'm trying to get data from my backend, when I click on the button for the first try it returns undefined, but on the second try everything works fine, someone have any suggestions that would fix this for me.

my provider function is below:

getArtisants(){
this.HttpClient.get('http://localhost/AlloMealem/backend/web/index.php?r=artisant/all').
        subscribe(result => {
            this.artisans=result;
        });
        return this.artisans;
    }

My service function that gets the data from the provider and put it in an array so I can use it in my components

 getArtisants() {
    this._artisans=this.searchProvider.getArtisants();
 } 
}

I expect to get my data in the first try because some of my pages should get data in the onInit() function which makes it important to get data in the first try.

  • return this.artisans; this line is causing it to return undefined initially as it is not waiting for subscribe to finish – Barkha Aug 08 '19 at 15:39
  • @user8351493 what do suggest to change. I not that familiar with Ionic. Thanks – Yassir Akhmis Aug 08 '19 at 15:40
  • Read the documentation. You are doing wrong things here. Your service should return a observable, and in the component you should subscribe. First of all this is asynchronous, secondly you cannot return from subscribe: https://angular.io/guide/http and also read https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – AJT82 Aug 08 '19 at 17:26
  • Check for `platform.ready()` and then invoke you http plugin , Platform ready promise will make sure all the plugins are loaded before you attempt to call them. – Maheswaran Ravisankar Aug 08 '19 at 18:51

1 Answers1

1

You can try this return an observable and then subscribe in calling function

getArtisants(){
return this.HttpClient.get('http://localhost/AlloMealem/backend/web/index.php?r=artisant/all')

    }

 getArtisants() {
   this.searchProvider.getArtisants().subscribe((res)=> { this._artisans=res;});
 } 
    ```

I have not used Ionic but hoping it will be similar to Angular
Barkha
  • 664
  • 3
  • 8