如何以角度取消/关闭行为主题
发布时间:2020-12-17 17:03:27 所属栏目:安全 来源:网络整理
导读:我有一个订阅了ngOnInit生命周期中的行为主题的组件.此组件html使用ngIf在呈现表之前查看数据是否存在. 当我离开页面时,我想确保下次回来时,表格不可见,直到再次获取该数据.到目前为止,我能够做到这一点的唯一方法是在主题上调用next并发送一个空字符串,这感
我有一个订阅了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> 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> 问题是,在没有向行为主题旁边发送空的情况下,mapMetaData仍然包含它从上一次下一次调用中收到的内容,导致该表显示我何时返回它,包含旧数据,然后在新数据时非常快速地更改收到了. 有没有更好的方法来处理这个问题,还是我正确地做到了? 解决方法
您可以使用asObservable()从您的BehaviorSubject获取Observable并存储订阅对象和ngOnDestroy您可以取消订阅:
在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(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |