1

I'm using RxJS subscribe to get data from my service, and then pass it to another function.

Everything works well but when I try to assign the same data to a public variable to use it somewhere, it returns undefined...

This is my public variable.

public prices: Array<any> = [];

This is my function:

getPriceData(book){

    //MarketService
    this.marketService.getPricesByBook(book).subscribe(data => {

        this.prices = data.payload;  // I want to assign the payload to a public variable to use later...

        //ChartingService
        this.price_data = this.chartService.getAveragePriceDataByTime(this.prices, this.interval);

    }, err => {
        console.log(err);
        return false;
    });

    console.log("Outside subscribe : ", this.prices); // Throws undefined 
}

Note that I want to reduce API calls since the data gets loaded at first (ngOnInit), I just want to let the user modify the data that's already loaded...

I'm open to suggestions on caching and/or saving the data to localStorage (if that's the case)

oschvr
  • 422
  • 7
  • 15
  • Why would `this.prices` be available immediately after the subscribe, when the subscribe handler will not run until the data is retrieved? –  May 21 '17 at 01:32
  • @torazaburo did u down vote ?? – Aravind May 21 '17 at 01:36
  • @torazaburo I get it, but how should I store the `payload` in `this.prices`in order to make it available later. , and is there any best practice from RxJS, that I could use to know when it is available? (Currently trying [BehaviorSubject](http://reactivex.io/rxjs/manual/overview.html#behaviorsubject)) – oschvr May 21 '17 at 01:42
  • @torazaburo thanks. – oschvr May 21 '17 at 01:49

0 Answers0