我对某些服务有以下订阅功能。
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
。
关于angular - 如何在 typescript 订阅功能之外获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41285965/