从RxJS5升级到版本6时遇到问题。我有以下代码:
private captureEvents(canvasEl: HTMLCanvasElement) {
Observable
.fromEvent(canvasEl, 'mousedown')
.switchMap((e) => {
return Observable
.fromEvent(canvasEl, 'mousemove')
.takeUntil(Observable.fromEvent(canvasEl, 'mouseup'))
.pairwise()
})
.subscribe((res: [MouseEvent, MouseEvent]) => {
const rect = canvasEl.getBoundingClientRect();
const prevPos = {
x: res[0].clientX - rect.left,
y: res[0].clientY - rect.top
};
const currentPos = {
x: res[1].clientX - rect.left,
y: res[1].clientY - rect.top
};
this.drawOnCanvas(prevPos, currentPos);
});
}
但是当我升级到RxJS6时,出现以下错误:
类型为“可观察的类型”的属性“ fromEvent”不存在。
我试图从此(RxJS5)更改导入:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/takeUntil';
import 'rxjs/add/operator/pairwise';
import 'rxjs/add/operator/switchMap';
对此(RxJS6):
import { Observable, fromEvent } from 'rxjs';
import { switchMap, takeUntil, pairwise } from 'rxjs/operators';
这是我升级代码的最佳尝试:
private captureEvents(canvasEl: HTMLCanvasElement) {
const obsMouseDown = fromEvent(canvasEl, 'mousedown').pipe(
switchMap((e) => {
const obsMouseMove = fromEvent(canvasEl, 'mousemove').pipe(
takeUntil(a => {
const obsMouseUp = fromEvent(canvasEl, 'mouseup').pipe(
pairwise()
);
return obsMouseUp;
}));
return obsMouseMove;
}))
.subscribe((res: [MouseEvent, MouseEvent]) => {
const rect = canvasEl.getBoundingClientRect();
const prevPos = {
x: res[0].clientX - rect.left,
y: res[0].clientY - rect.top
};
const currentPos = {
x: res[1].clientX - rect.left,
y: res[1].clientY - rect.top
};
this.drawOnCanvas(prevPos, currentPos);
});
}
但这无法正常工作-我收到“ takeUntil”代码的错误:
类型'(a:any)=> Observable <[Event,Event]>'的参数不是 可分配给“可观察”类型的参数
plnkr原始代码示例在这里:
https://embed.plnkr.co/QSvJxi/
答案 0 :(得分:1)
fromEvent
现在已经是Observable类型。您不需要将其链接到Observebal,而是可以直接调用它并将其影响到变量或更好的const。如下所示:
const source = fromEvent(document, 'click');
对于导入,您认为正确
import { fromEvent } from 'rxjs';
答案 1 :(得分:1)
由于某种原因,您的plnkr不适用于我,但我会尽力提供答案。我认为您应该在这里做2件事。尝试初始化您的Observable,以便像这样轻松地调用它们并进行订阅:
const mousedown$ = fromEvent(pauseButton, 'mousedown');
const mouseup$ = fromEvent(resumeButton, 'mouseup');
const mousemove$ = fromEvent(resumeButton, 'mousemove');
第二点,您现在应该像这样用Rxjs 5和6来传递操作员,并订阅所有事件
mousedown$.pipe(
switchMap(res => {
mousemove$.pipe(//Whatever Operators and subscribitions to other events).subscribe(...)
}),
map(// Whatever you want back from your event)
).subscribe(...)
我指的是文档链接switchMap && takeUntil。由于Rxjs中的许多语法都在变化,因此不要羞于浏览文档,没有什么比这更好的了。
答案 2 :(得分:1)
我认为您实际上非常接近,但我认为您的管道太“深”了-请记住,您可以在管道中将所需的多个运算符链接在一起,因此内部鼠标可以移动直到鼠标移开switchmap应该看起来像这样:
private captureEvents(canvasEl: HTMLCanvasElement) {
const obsMouseDown = fromEvent(canvasEl, 'mousedown').pipe(
switchMap((e) => {
return fromEvent(canvasEl, 'mousemove').pipe(
takeUntil(a => fromEvent(canvasEl, 'mouseup')),
pairwise()
));
}))
.subscribe((res: [MouseEvent, MouseEvent]) => {
// snip
});
}