我有一个实现,当使用takeUntil销毁组件时,它会自动取消可观察到的订阅。但是在许多组件中实现相同的代码是很烦人的。
我想知道这是否可以简化(我不能使用async管道,因为我需要在类型记录组件中发出的值)
以下是我目前的实现:
export class Component implements OnDestroy {
_dstr = new Subject();
data$: Observable<any> = this.store.select(Selector.getData);
constructor(
private store: Store<State>,
) {
this.store.pipe(
select(Selector.getOtherData),
takeUntil(this._dstr),
).subscribe(data => {
console.log('here is my data!', data)
});
}
public ngOnDestroy(): void {
this._dstr.next();
this._dstr.complete();
}
}发布于 2018-12-09 10:54:30
您可以收集数组中的所有订阅,并在ngOnDestroy函数中取消订阅每个订阅。如果您经常需要这种行为,您可以考虑使用一个抽象类,从抽象类中扩展所有为您服务的组件。
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription, Observable, of } from 'rxjs';
export abstract class BaseComponent implements OnDestroy{
public subscriptions: Subscription[] = [];
public ngOnDestroy(): void {
console.log("destroyed");
this.subscriptions.forEach(s => s.unsubscribe());
}
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
}
let count: number = 0;
@Component(
{
selector: 'app-derived',
template: 'Derived Class'
}
)
export class DerivedComponent extends BaseComponent implements OnInit, OnDestroy {
private store: Observable<any> = of(count++);
constructor() {
super();
}
public ngOnInit(): void {
this.subscriptions.push( this.store.subscribe(data => console.log(data)) );
}
}https://stackoverflow.com/questions/53691396
复制相似问题