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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41285965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:06:45  来源:igfitidea点击:

How to get value outside typescript subscribe function

angulartypescript

提问by LearnToday

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.valueObjin the following functions outside the subscribe function.

这似乎没问题。除了我需要在订阅函数之外的以下函数中使用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);
  }

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

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

采纳答案by Günter Z?chbauer

Async calls need to be properly chained.

异步调用需要正确链接。

If you return an observable (requires mapinstead of subscribe)

如果你返回一个 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; 
     });
  });
}

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.valueObjlooong before the value becomes available.

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