Angular 7 个行为主体与 class 个客体

Angular 7 behavior subject with class object

我有以下class

export class filter {
    public PageRecords: number;
    public SearchText: string;
    public SortColumn: string = null;
    public SortDirection: string = null;
    public StartingPos: number;
}

以下行为主体

filterParam = new BehaviorSubject(new filter);

更新主题

this.filterParam.next(<filter>{StartingPos  : 1,PageRecords : 10 })

当我得到subject的值时

this.filterParam.value

它只有我更新的两个道具StartingPos和PageRecords。它失去了其他道具。

如何解决?

这是因为你没有直接传递一个过滤器对象class。您正在将一些动态 json 投射到过滤器对象,但仅具有这两个属性。

你可以这样做:

const filterParam = new filter();
filterParam.StartingPos = 1;
filterParam.PageRecords = 10;

this.filterParam.next(filterParam);

编辑: 我没有注意到您只想更新 BehaviorSubject 值中的两个值。正如@ritaj 在下面的评论中建议的那样,你可以像他建议的那样做:

this.filterParam.next(Object.assign(this.filterParam.value, {StartingPos: 1, PageRecords: 10 }

Object.assign() copies the values (of all enumerable own properties) from one or more source objects to a target object. It has a signature of Object.assign(target, ...sources). The target object is the first parameter and is also used as the return value. Object.assign() is useful for merging objects or cloning them shallowly.

根据您的 class 参数名称的含义,我认为您想要一个 filter class 并且您只想在更改此过滤器时通知其他人。

我推荐这个代码:

filter = new filter;
filterParam = new BehaviorSubject<filter>(this.filter);

// later change the filter like this
changeFilter() {
  this.filter.StartingPos = 1;
  this.filter.PageRecords = 10;
  this.filterParam.next(this.filter);
}