Bla*_*axy 2 rxjs typescript angular
我尝试获得窗口innerWidth的可观察值。
我fromEvent对尺寸调整事件设置了可观察的观看
public get nativeWindow(): Window {
return window;
}
public getWindowSize(): Observable<number> {
return fromEvent(this.nativeWindow, 'resize').pipe(
map(event => (event.target as Window).innerWidth)
);
}
Run Code Online (Sandbox Code Playgroud)
我希望能够获取window.innerWidth的初始值,因为在实际调整窗口大小之前不会触发调整大小。
我可以使用,BehaviorSubject但它迫使我订阅fromEvent下一个主题。
我们尝试startWith(this.nativeWindow.innerWidth)在地图之前使用运算符,但随后地图没有将event参数作为Event而是获取了startWith数字。
是否有任何rxjs运算符可以让我在获取实际的调整大小事件之前初始化第一个数字?
因此,问题在于您需要map处理初始值,但同时又需要它与Event仅由'resize'事件发出的对象一起使用。
那么最简单的方法是只使用startWith后map:
return fromEvent(this.nativeWindow, 'resize').pipe(
map(event => (event.target as Window).innerWidth),
startWith(this.nativeWindow.innerWidth)
);
Run Code Online (Sandbox Code Playgroud)
或者,如果不可能(例如,逻辑更复杂),则可以“模拟”对象,以便map像处理其他任何Event对象一样处理它。
return fromEvent(this.nativeWindow, 'resize').pipe(
startWith({ target: { innerWidth: this.nativeWindow.innerWidth }}),
map(event => (event.target as Window).innerWidth)
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
554 次 |
| 最近记录: |