[英]Angular2 EventEmitter with last value
Basically I want to know is there a way to get last value from EventEmmiter
right after I have subscribed to it?基本上我想知道有没有办法在我订阅
EventEmmiter
后立即从EventEmmiter
获取最后一个值?
Why I need this.为什么我需要这个。 Imagine a list component that uses two more components: filter and grid.
想象一个列表组件,它使用了另外两个组件:过滤器和网格。 Filter provides
filter
event and grid provides sorting
event. Filter 提供
filter
事件,grid 提供sorting
事件。
In my list component I want to write code like this:在我的列表组件中,我想编写这样的代码:
Observable
.combineLatest(filtering$, sorting$)
.switchMap(([filter, sorting]) => {
return this.api.list(filter, sorting);
})
...
Very short elegant code.非常简短的优雅代码。 But there are two problems:
但是有两个问题:
EventEmitter
is not observable . EventEmitter
是不可观察的。 It is not much of a problem because I can easily wrap it with observable. Currently I am solving it with BehaviorSubject
from RxJs:目前我正在使用 RxJs 的
BehaviorSubject
解决它:
Represents a value that changes over time.
表示随时间变化的值。 Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
观察者可以订阅主题以接收最后(或初始)值和所有后续通知。
In my filter component I have:在我的过滤器组件中,我有:
class UsersListFilter {
private filteringSource = new BehaviorSubject<UserFilter>(new UserFilter());
filtering$ = this.filteringSource.asObservable();
...
}
And in my list component:在我的列表组件中:
class UsersList {
@ViewChild(UsersListFilter) private filter: UsersListFilter;
...
setupDataReloading() {
Observable
.combineLatest(this.filter.filtering$, this.grid.sorting$)
...
}
}
As you can see I do not use EventEmitter
at all.如您所见,我根本不使用
EventEmitter
。 But this solution feels kinda unnatural in Angular2 because I am ignoring standard way of interacting with child component ( @Output
).但是这个解决方案在 Angular2 中感觉有点不自然,因为我忽略了与子组件(
@Output
)交互的标准方式。
Any thoughts?有什么想法吗?
Use this custom class instead改用这个自定义类
import { EventEmitter } from '@angular/core';
import { ObjectUnsubscribedError } from 'rxjs';
export class CustomEventEmitter<T> extends EventEmitter<T> {
private _value: T;
constructor() {
super();
}
get value(): T {
return this.getValue();
}
getValue(): T {
if (this.hasError) {
throw this.thrownError;
} else if (this.closed) {
throw new ObjectUnsubscribedError();
} else {
return this._value;
}
}
emit(value?: T) {
super.emit(this._value = value);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.