如何订阅变量更改?

时间:2018-10-23 12:33:21

标签: angular typescript rxjs

我声明了以下变量:

public filter: IFilterWeekScheduleClassShort = {};

如何订阅更改(监听对象过滤器)?

我尝试过:

private filter: IFilterWeekScheduleClassShort = {};
private filterChanges: BehaviorSubject<IFilterWeekScheduleClassShort> = new BehaviorSubject(this.filter);

this.filterChanges.subscribe((model) => {
    console.log(model);
});

可以吗?

我的最终代码:

public _filter: IFilterWeekScheduleClassShort = {};
private filterChanges: BehaviorSubject<IFilterWeekScheduleClassShort> = new BehaviorSubject(this._filter);

  this.filter = {a: 1, b: 2}

  set filter(value: any) {
    this._filter = value;
    this.filterChanges.next(this._filter);
  }

  get filter() {
    return this.filterChanges.asObservable();
  }

订阅:

this.filter.subscribe(model => {
   console.log(model);
});

我从表单进行的更改:

[(ngModel)]="_filter.teacherId"

2 个答案:

答案 0 :(得分:6)

做个二传手

private _filter: IFilterWeekScheduleClassShort = {};
set filter(value) {
  this.doSomethingOnVariableChange(value);
  this._filter = value;
}

现在您可以像这样使用它

this.filter = 'x';

然后您的函数doSomethingOnVariableChange将被'x'调用。

具有可观察到的:

private _filter: IFilterWeekScheduleClassShort = {};
private _filter$ = new BehaviorSubject(this._filter);
set filter(value) {
  this._filter = value;
  this._filter$.next(this._filter);
}
get filter() {
  return this._filter$.asObservable();
}

答案 1 :(得分:0)

我认为您要使用scan()的结局:

const filterChanges$ = new Subject()
const defaultFilter = {}

const filter$ = filterChanges$
  .pipe(
    scan((acc, mergeFilter) => {
      return {
        ...acc,
        ...mergeFilter,
      }
    }, defaultFilter)
  )

filter$.subscribe(console.log);

filterChanges$.next({ name: 'abc' })
filterChanges$.next({ num: 42 })
filterChanges$.next({ name: 'xyz' })

实时演示:https://stackblitz.com/edit/rxjs6-demo-ngqkzv?file=index.ts

这将输出:

{name: "abc"}
{name: "abc", num: 42}
{name: "xyz", num: 42}

前段时间,我在window.Proxy周围做了一个小包装,称为rxjs-observable-object,可用于包装任何对象,然后听其上的变化(https://github.com/martinsik/rxjs-ds#object):

import { map } from 'rxjs/operators';
import { ObservableObject } from 'rxjs-observable-object';

const defaultFilter = {}
const { proxy, events } = new ObservableObject(defaultFilter);

const filter$ = events.onSet
  .pipe(
    map(({ target }) => target)
  )

filter$.subscribe(console.log);

proxy['name'] = 'abc';
proxy['num'] = 42;
proxy['name'] = 'xyz';

实时演示:https://stackblitz.com/edit/rxjs6-demo-hojjkk?file=index.ts

但是,rxjs-observable-object现在有点过时了,并且还需要安装rxjs-comapt软件包。

两个示例的输出相同。