Hi iam developing an app, where i have userService class, that manages user data. Here i create observable like this :
export class UserService {
currentUser;
userObservable;
userObserver;
constructor(public http: Http,private db:Database, private platform:Platform) {
this.platform.ready().then(()=>{
this.userObservable=Observable.create(observer=>{
this.userObserver=observer;
setTimeout(()=>{
this.getCurrentUser().then((data)=>{
this.userObserver.next(this.currentUser);
});
},600);
}).publish();
this.userObservable.connect();
});
}
saveUser(user){
this.db.insertUserToUsers(user).then(()=>{
this.currentUser=user;
this.userObserver.next(this.currentUser);
});
}
getCurrentUser(){
return new Promise(resolve=>{
this.db.getUser().then((data)=>{
this.currentUser=data;
resolve(this.currentUser);
});
});
}
Then i subscribe to it at home page and at user page in constructor like this :
this.platform.ready().then(() => {
this.userService.getCurrentUser().then((data)=>{
this.currentUser=data;
});
this.userSubscription=this.userService.userObservable.subscribe((data)=>{
console.log(data);
this.currentUser=data;
});
The problem is, the observable start to emit values,everything is ok but homepage, but it doesnt work on user page, because it isnt subscribed in the moment when the observable starts emitting. Is there any way to fix this problem? If i use observable without publish() and connect(), it doesnt work too, because for some reason - home page subscription ok, user page subscription ok, but after this, the first subscription(subscription from home page) stops to work. Any ideas?