如何取消/关闭 Angular 中的行为主体

2024-05-09

我有一个订阅了行为主题的组件ngOnInit生命周期。该组件 html 使用ngIf在渲染表格之前查看数据是否存在。

当我离开该页面时,我想确保下次返回时,该表不可见,直到再次获取该数据。到目前为止,我能够做到这一点的唯一方法是调用该主题的 next 并发送一个空字符串,这感觉不对。

成分:

mapMetaData: any;

ngOnInit() {

    // Subscribe to our map data
    this._mapsService.uiMapMetaData
    .subscribe(
        results => {
            if (results) {
                this.mapMetaData = results;
            }
        }
    );

}

/**
 * Implement onDestroy life cycle
 * 
 * @memberof ViewMapComponent
 */
ngOnDestroy() {
    this._mapsService.updateMapMetaData('');
}

HTML:

<span *ngIf="mapMetaData">
    <div class="page-header">
        <h3 class="text-primary">{{ mapMetaData.TargetName }} <small>{{ mapMetaData.TargetDesc }}</small>
            <button type="button" class="btn btn-default btn-sm pull-right" role="button" (click)="backToMaps()">
                <i class="fa fa-arrow-left"></i>&nbsp;&nbsp;Back to Maps
            </button>
        </h3>
    </div>
    <app-map-versions [targetID]="targetID"></app-map-versions>
    <app-map-exceptions [targetID]="targetID"></app-map-exceptions>
    <app-map-rules></app-map-rules>
</span>

问题是,不发送空next对于行为主体来说,mapMetaData仍然包含从之前收到的内容next调用,导致表格显示当我返回时包含旧数据,然后在收到新数据时很快发生变化。

有更好的方法来处理这个问题还是我做得正确?


您可以使用asObservable()得到一个Observable来自你BehaviorSubject并存储订阅对象和ngOnDestroy你可以unsubscribe :

在你的mapServie类中:

 private mapSubject = new BehaviorSubject<any>(mapdata()); /* you get the idea */
 public mapObservable = this.mapSubject .asObservable();

然后您可以执行以下操作:

mapMetaData: any;
subscription: Subscription;
ngOnInit() {

    this.subscription = this._mapsService.uiMapMetaData
    .subscribe(
        results => {
            if (results) {
                this.mapMetaData = results;
            }
        }
    );

}
ngOnDestroy() {
    this.subscription.unsubscribe();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何取消/关闭 Angular 中的行为主体 的相关文章

随机推荐