Get data in subscribe


#1

Why

  test: any[];

  constructor(public navCtrl: NavController, public navParams: NavParams, public service: ServiceProvider, public loadingCtrl: LoadingController) {
    this.method1();
  }

  method1() {
    this.service.getData()
        .subscribe(
          data => this.test= data,
          e => console.log(e)
        );
  }

I’m trying get “this.test” in method2

method2() {
  this.otherList= [];
  console.log(this.test);
  // for(let t of this.test) {
  //   console.log(t);
  // }
}

Why this.test to show in console undefined ?


#2

Given only what you’ve told us so far, all I can say is “because you called method2() before getData() resolved”.

You should do your best to design things so that you don’t have these sorts of situations. method2() needs to be able to function regardless of whether this.test has been populated yet, or its functionality can be folded into the subscription of method1(), or it can to do its own subscription. Explicitly attempting to synchronize (such as with semaphores) is sort of antithetical to how asynchronous JavaScript programming is intended to be written.

My general design pattern here is to have service providers expose somehow (either as properties or return values of methods) Observables of business object interfaces. Pages inject these providers, subscribe to them either at construction or using lifecycle events, and update their own properties accordingly. All other page methods and templates should be written so as not to particularly care whether these page properties derived from provider data are blank/dummy, loaded, or modified while they are not paying attention.


#3

Your using both Synchronous(method 2) & Async(method 1).

The reason why you cannot get “this.test” even when you write your code like this is because:

method1();
method2();

it will run the method1 and method 2
method 2 will finish first but method1 is not yet finish.
that is why you have the “subscribe” in method1 to observe if there is a result.

As you can see you are dealing with an observable (method 1).
The best way to get the data pass to the “this.test” is put the “method 2” inside the observable, like this

method1().subscribe(
    this.test = data;
    //call the synchronous method here
    this.method2();
);

a good article to have an idea with sync/async is this : https://www.joshmorony.com/dealing-with-asynchronous-code-in-ionic/


#4

Thanks for your help, I did it!
I was using

  method1() {
    this.service.getData()
         .subscribe(
           data => this.test = data,
           e => console.log(e)
         );
  }

This not work, tnks my friend!