LearnToday
LearnToday

Reputation: 2902

How to get value outside typescript subscribe function

I have the following subscribe function for some service.

this.sub = this.route.params.subscribe(params => {
this.id = params['id'];
this._someService
      .thisById(this.id)
      .subscribe(value => {
         this.valueObj = value; 
     });
});

This seems all right. Except that I need to use the this.valueObj in the following functions outside the subscribe function.

private  _checkOpeningHours(data: any): string {
    const curDayName = this._getDayName();
    const todaysOpeningData = ***this.valueObj***.openHours[curDayName];

    if (!todaysOpeningData) return "ERROR!";
    if (!todaysOpeningData.status) return `IT'S ${curDayName.toUpperCase()} - WE ARE CLOSED TODAY!`;

    return `IT'S ${curDayName.toUpperCase()}, ${new Date().toLocaleString("en-US", { hour: '2-digit', minute: '2-digit' })} - ${this._isOpen(todaysOpeningData) ? 'WE ARE OPEN' : 'SORRY, WE ARE CLOSED'}!`;

  }

  private _refresh() {
    this.opening = this._checkOpeningHours(***this.valueObj***.openHours[this._getDayName()]);

    setTimeout(() => this._refresh(), 60 * 1000);
  }

How can I get these functions to work with the this.valueObj?

Upvotes: 6

Views: 20455

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658235

Async calls need to be properly chained.

If you return an observable (requires map instead of subscribe)

someMethod() {
  this.sub = this.route.params.subscribe(params => {
  this.id = params['id'];
  return this._someService
      .thisById(this.id)
      .map(value => {
         return this.valueObj = value; 
     });
  });
}

then you can use it like

private  _checkOpeningHours(data: any): string {
  this.someMethod().subscribe(val => {
    console.log(val); // here the value is available
  });
}

Without proper chaining it's very likely that _checkOpeningHours() accesses this.valueObj looong before the value becomes available.

Upvotes: 6

Related Questions