我建议你重新调整你的服务 . 这样做吧 .
您不允许订阅者订阅数据 - 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();
}
}
这应该做 .