我有一些服务的订阅功能。
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 一起使用?
答案 0 :(得分:4)
需要正确链接异步调用。
如果您返回可观察对象(需要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
。