我对某些服务有以下订阅功能。
this.sub = this.route.params.subscribe(params => {
this.id = params['id'];
this._someService
.thisById(this.id)
.subscribe(value => {
this.valueObj = value;
});
});
这看起来没问题。除了我需要使用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);
}
我怎样才能让这些功能与this.valueObj?
异步调用需要正确链接。
如果你返回一个可观察的(需要map
代替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;
});
});
}
那么你可以像这样使用它
private _checkOpeningHours(data: any): string {
this.someMethod().subscribe(val => {
console.log(val); // here the value is available
});
}
如果没有正确的链接,很可能_checkOpeningHours()
访问this.valueObj
在该值变得可用之前很长时间。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)