Angular组件:我可以使用Observable而不是EventEmitter作为@Output()属性吗?

ber*_*ndg 18 rxjs eventemitter angular

[棱角2.4.5]

我尝试过它似乎像EventEmitter一样工作:

  • 来自外部的我的组件:

    <split (visibleTransitionEnd)="log($event)"></split>
    
    Run Code Online (Sandbox Code Playgroud)
  • 组件内部:

    @Output() visibleTransitionEnd: Observable<string>
    observer: Observer;
    
    constructor() {
      const myObs = new Observable(observer => this.observer = observer);
    
      this.visibleTransitionEnd = myObs
        .map(x => '> ' + x + ' <')
        .debounceTime(20)
        .do(() => console.log('here we are!'));
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 然后我可以调用内部组件:

    // needed condition because if nobody subscribe 'visibleTransitionEnd' > no observer!
    if(this.observer) this.observer.next('test');
    
    Run Code Online (Sandbox Code Playgroud)

查看此plunker

我喜欢这个,因为我的组件中没有订阅.

但这是一个不好的方法吗?什么是风险/错误?

使用它更好Subject吗?

Gün*_*uer 9

EventEmitter只是延伸Subject,所以这并不奇怪(我也在Dart中看到了这一点).

他们使用自己的类能够在不破坏现有代码的情况下更改实现.

因此,绕过这种抽象可能不是最好的主意.如果你意识到这种劣势并愿意接受它,你当然可以这样做.


mar*_*tin 7

那么,在你的情况下,你可以使用EventEmitterSubject.您可以看到a EventEmitter就像Subject(尽管EventEmitter如果可以的话,建议使用它).https://github.com/angular/angular/blob/master/modules/%40angular/facade/src/async.ts

Observable.create(或new Observable())不旨在这样被使用.内部函数应该向观察者发出值并返回拆除函数(以释放资源或其他).不得作为财产保留.
但是,我不确定它会带来什么后果(内存泄漏?).

所以Subject改为使用:

export class SplitComponent implements OnDestroy {
  @Output() visibleTransitionEnd: Observable<string>
  visibleTransitionEndObserver: Subject;

  constructor() {
    const subject = new Subject();

    this.visibleTransitionEnd = subject.asObservable()
      .map(x => '> ' + x + ' <')
      .debounceTime(20)
      .do(() => console.log('here we are!'));
  }

  // ...
}
Run Code Online (Sandbox Code Playgroud)