【问题标题】:How to trigger an rxjs observable如何触发 rxjs observable
【发布时间】:2018-06-29 19:19:51
【问题描述】:

使用 rxjs v6

所以我有多个要跟踪/观察的变量,当其中任何一个发生变化时,触发 Observable 调用 API,然后根据这些变量更新其他内容。

我想我可能会在 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)

但是,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
                    }
                })
            }    
        })
    )

【问题讨论】:

  • update 是自定义事件监听器吗?因为据我所知,没有名为 update 的事件监听器
  • @JacobGoh 是的,我会更新我的实现方式。只是额外说明 Observable 已创建,但我无法像预期的那样订阅
  • 您能否详细说明“observable 上没有订阅方法” 以及您发布的两个 sn-ps 是如何交互的?

标签: javascript rxjs rxjs6


【解决方案1】:

根据您的问题标题,我推测您的自定义事件只是达到目的的一种手段。

如果是这样,我认为实际上没有必要。如果您希望“外部” 影响(或触发)可观察对象,请使用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$);
<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>

【讨论】:

  • 这看起来像我想要做的。我会试一试,让你知道
  • 这是正确的做法吗?我主要只是想更新/触发一些变量更改的可观察对象(我正在使用 Vue)。但它正在工作。
  • 我宁愿尝试组合 observables,但有时主题也有它们的用处。
猜你喜欢
  • 1970-01-01
  • 2019-12-02
  • 2022-07-11
  • 2020-01-31
  • 2017-02-15
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
相关资源
最近更新 更多