我有一个共享服务如下:
data = new BehaviorSubject<any[]>([]);
constructor(userService: UserService){
if (localStorage.getItem('data') === null) {
userService.getAllData().subscribe(results =>
this.data.next(results)
}
else {
this.loadData()
}
}
loadData() {
let data = JSON.parse(localStorage.getItem('data');
this.data.next(data);
}
setData(data) {
localStorage.setItem('data', JSON.stringify(data))
this.data.next(data)
}
Run Code Online (Sandbox Code Playgroud)
然后在我的 ngOnInit() 组件上,我有:
ngOnInit() {
this.sharedService.data.subscribe(results =>
this.allData = results;
)
}
itemChange() {
this.allData.slice(index, 5);
this.sharedService.data.next(this.allData)
}
Run Code Online (Sandbox Code Playgroud)
和 OnLogout 我有:
localStorage.removeItem('data')
Run Code Online (Sandbox Code Playgroud)
问题是在第一页重新加载时,服务被调用并且我按预期获得了数据,我进行了更改,然后在我注销并重新登录后,在存储上我不再拥有数据密钥,但是sharedService 不会再次被调用,而是在this.sharedService.data上次填充的onInit 组件上。
我如何让它每次都调用 sharedService 以便它检查 item('data') 是否存在,就像它在服务构造函数上一样?
我建议你重组你的服务。这样做。
你不让订阅者订阅数据行为主题本身,而是订阅一个 getter-method,将你的对象作为 Observable 返回。效果相同,但您现在可以在订阅发生时另外调用其他私有方法。
import { Observable } from 'rxjs/Observable';
private data = new BehaviorSubject<any[]>([]);
constructor(private userService: UserService){}
getData(): Observable<Array<any>> {
// called once with/by each subscription
this.updateData();
return this.data.asObservable();
}
Run Code Online (Sandbox Code Playgroud)
现在,您对每个新订阅都调用私有方法 updateData()。此方法将执行您当前在构造函数中所做的检查。但是,这种检查现在不仅会在服务实例化时发生一次,而且会在每次新运行应用程序时发生,无论您是关闭浏览器还是简单地注销。
getDataValue(): Array<any> {
return this.data.getValue();
}
setData(val: Array<any>) {
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));
}
}
Run Code Online (Sandbox Code Playgroud)
在您的组件中:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这个应该可以。