如何在打字稿订阅功能之外获取价值

Lea*_*day 6 typescript angular

对于某些服务,我有以下订阅功能。

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

这似乎没问题。除了我需要在 subscribe 函数之外的以下函数中使用this.valueObj

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);
  }
Run Code Online (Sandbox Code Playgroud)

我怎样才能让这些函数与this.valueObj一起工作?

Gün*_*uer 6

异步调用需要正确链接。

如果你返回一个 observable (requiresmap而不是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; 
     });
  });
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它

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

如果没有适当的链接,很可能在值可用之前_checkOpeningHours()访问this.valueObjlooong。