我一直在开发一个允许几个不同组件更新 BehaviorSubject
的应用程序。在 Angular 。在每个组件中,我存储了前一个 BehaviorSubject
的本地副本值(value)。为了知道组件是否生成了被推出的新值,我打算只使用 LoDash 的 _.isEqual()
比较两个对象。功能。但是,我发现在进行比较之前,我的 Observable 本地副本已经更新。
Angular 是否寻找 =
语句并在 Observable next
之外创建到该组件属性的外部绑定(bind)功能?
鉴于下面的代码,我发现我的 this.QueryParams
组件内的属性已更新为函数中正在处理的当前值,导致比较失败,即使我直到 if
才将新值分配给属性。声明已被评估。
组件
export class LogsModalComponent implements OnInit {
private QueryParams: LogsQueryParameters
ngOnInit() {
this._LogsService.QueryParameters$.subscribe(_QueryParams => {
console.log(this.QueryParams);
console.log(_QueryParams);
if (!_.isEqual(this.QueryParams, _QueryParams) {
this.QueryParams = _QueryParams;
// Some code to process if the new value was different.
}
}
}
updateStartDate() {
this.QueryParams.filterStartDate = _.isUndefined(this.FilterStartDate) ? NaN : new Date(this.FilterStartDate.nativeElement.value).getTime();
this._LogsService.updateQueryParams(this.QueryParams);
}
}
服务
LogsQueryParameters: BehaviorSubject<LogsQueryParameters> = new BehaviorSubject<LogsQueryParameters>({
limit: 25,
logLevels: "",
logTypes: "",
logUserIDs: "",
filterStartDate: NaN,
filterEndDate: NaN
})
LogsQueryParameters$ = this.LogsQueryParameters.asObservable();
updateQueryParams(QueryParams) {
this.LogsQueryParameters.next(QueryParams);
}
最佳答案
RxJS observables 有一个方法 distinctUntilChanged()
它返回一个新的 observable,如果它与之前发出的值不同,它只会发出一个新值:
this._LogsService.QueryParameters
.distinctUntilChanged()
.subscribe((_QueryParams) => this.QueryParams = _QueryParams);
这适用于简单的比较。如果您需要
_.isEqual
不过,您可以将回调传递给 distinctUntilChanged()
改为执行比较:this._LogsService.QueryParameters
.distinctUntilChanged((prev, curr) => _.isEqual(prev, curr))
.subscribe((_QueryParams) => this.QueryParams = _QueryParams);
请注意,您不会返回
! ...
在回调内部,只要返回值为 false
(意味着被测值不相等),值通过。更新
从您的最新编辑看来,您实际上是在传递完全相同的对象,并且只是改变其内容,正如@Brandon 在下面的评论中所建议的那样。您可以尝试在更新时创建一个新对象,通过
Object.assign()
:updateStartDate() {
this.QueryParams.filterStartDate = _.isUndefined(this.FilterStartDate)
? NaN
: new Date(this.FilterStartDate.nativeElement.value).getTime();
this._LogsService.updateQueryParams(Object.assign({}, this.QueryParams));
}
对象实际上是通过引用传递的。
请注意
new Date()
还会返回一个对象。该对象也通过引用传递和分配,只是这次 Object.assign
不会帮助你,因为日期对象取决于原型(prototype)链接(它不是一个普通的对象)。
关于angular - 比较 Observable 的前一个值和 Angular 中的下一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46203449/