A. *_*Lau 3 javascript rxjs rxjs6
使用 rxjs v6
因此,我有多个要跟踪/观察的变量,当其中任何一个发生变化时,触发 Observable 调用 API,然后根据这些变量更新其他内容。
我以为我可以在 a 上触发一个事件div来强制 observable 做某事,但它不会根据我想要的结果返回结果
例如
var a, b, c, d // if any updates, should trigger div "update" event
let obs = fromEvent(this.$refs.updater, "update")
.pipe(
switchMap(i => {return this.callAnAPI()})
)
obs.subscribe()
var update = new Event("update")
this.$refs.updater.dispatchEvent(update)
Run Code Online (Sandbox Code Playgroud)
但是,在 observable 上没有 subscribe 方法。我试图修改我的其他 Observable 之一(有效)
fromEvent(input, "keyup")
.pipe(
map(i => i.currentTarget.value),
debounceTime(delay),
distinctUntilChanged(),
switchMap(value =>
{
this.page = 1
if (ajax)
{
return ajax
}
else
{
return this.axiosAjax({
path,
method,
data: {
...data,
[term]: value
}
})
}
})
)
Run Code Online (Sandbox Code Playgroud)
根据您问题的标题,我推测您的自定义事件只是达到目的的一种手段。
如果是这样,我认为实际上没有必要。如果您想对 observable 产生“外部”影响(或触发器),请使用Subject.
例如:
const { fromEvent, merge, of, Subject } = rxjs;
const { switchMap, delay } = rxjs.operators;
// fake api
const fakeApi$ = of(Math.random()).pipe(
delay(2000),
);
// store a reference to the subject
const triggerApi$ = new Subject();
// apply behavior
const api$ = triggerApi$.pipe(
switchMap(
() => {
console.log('switching to api call');
// delegate to api call
return fakeApi$;
}
)
);
// activate (handle result)
api$.subscribe((result) => {
console.log('api result', result);
});
// some outside triggers
const fooClicks$ = fromEvent(document.getElementById('foo'), 'click');
const barClicks$ = fromEvent(document.getElementById('bar'), 'click');
const bazChanges$ = fromEvent(document.getElementById('baz'), 'change');
// combined
const updates$ = merge(fooClicks$, barClicks$, bazChanges$);
// activate
updates$.subscribe(triggerApi$);Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/rxjs@6.2.1/bundles/rxjs.umd.min.js"></script>
<button id="foo">foo</button>
<button id="bar">bar</button>
<textarea id="baz"></textarea>Run Code Online (Sandbox Code Playgroud)