java 注销变量_BehaviorSubject变量在注销后保留数据

本文介绍了如何在Java中使用BehaviorSubject时确保在组件注销后正确清理数据。建议通过调整服务,让每个订阅者在订阅时调用更新数据的方法,而不是直接订阅BehaviorSubject。同时,提供了实现这个功能的代码示例,包括使用localStorage存储数据并在初始化时从localStorage加载或从服务器获取数据。在组件的ngOnInit和ngOnDestroy中分别进行订阅和取消订阅操作,以确保数据在组件生命周期中的正确管理。
摘要由CSDN通过智能技术生成

我建议你重新调整你的服务 . 这样做吧 .

您不允许订阅者订阅数据 - BehaviorSubject本身,而是订阅getter方法,而不是将对象作为Observable返回 . 相同的效果,但您现在可以在订阅发生时另外调用其他私有方法 .

import { Observable } from 'rxjs/Observable';

private data = new BehaviorSubject([]);

constructor(private userService: UserService){}

getData(): Observable> {

// called once with/by each subscription

this.updateData();

return this.data.asObservable();

}

现在,您可以使用每个新订阅调用私有方法updateData() . 此方法将执行您当前在构造函数中执行的检查 . 但是,这项检查现在不仅会在服务实例化时发生一次,而且每次运行新应用程序时都会关闭浏览器或只是注销 .

getDataValue(): Array {

return this.data.getValue();

}

setData(val: Array) {

localStorage.setItem('data', JSON.stringify(val));

this.data.next(val);

}

private updateData(): void {

const storage = localStorage.getItem('data');

if (storage === null) {

this.userService.getAllData().subscribe(results => {

this.data.next(results);

}

} else {

this.data.next(JSON.parse(storage));

}

}

在你的组件中:

import { Subscription } from 'rxjs/Rx';

private subscription: Subscription;

ngOnInit() {

this. subscription = this.sharedService.getData().subscribe(results =>

this.allData = results;

)

}

ngOnDestroy() {

if (this.subscription) {

this.subscription.unsubscribe();

}

}

这应该做 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值