Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 372
LearnToday Avatar asked Dec 22 '16 14:12

LearnToday


People also ask

How do you access value outside the subscribe in angular?

You can't get the value outside of subscribe . You can use map and return the result for the caller to subscribe, like done in getDisabledDate or you move the code to one of the callbacks. I am trying to use data returned from an Angular Observable Service in a function outside the subscription. You cannot do this.

How does Angular subscribe work?

Subscribinglink An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications. Returns an Observable instance that synchronously delivers the values provided as arguments.


1 Answers

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.

like image 162
Günter Zöchbauer Avatar answered Nov 13 '22 06:11

Günter Zöchbauer