I'm sure this is an easy problem, I just don't know where to pinpoint it. I have an UserProfile service that creates a BehaviorSubject for the userdata. When I log in I use this service to broadcast the userdata. Once logged in I subscribe to this userdata in my Dashbord component. But the userdata observable is only returning the first empty object when I first created the BehaviorSubject. It is as if the login function that pushes the new data with .next() is only running after the dashboard subscribed to the BehaviourSubject. I tried putting the subscribe of my dashboard in ngAfterContentInit() so that the .next() runs before the subscription, but I'm still getting a blank object. If I run a .next() via set_new_data() function within my dashbord to check if the observable work, I get the data passed by .next(); But I don't get the data my login-component set via the set_userdata() function within my service.
Can we not share data like this using a service? Is the service destroyed after leaving the login component or what is happening?
My USerProfile Service:
@Injectable()
export class UserProfileService {
public isLoggedIn: boolean = false;
public userdata: BehaviorSubject<any> = new BehaviorSubject<any>({});
constructor() {
}
public set_userdata(data) {
// this.userdata = data;
console.log(this.userdata);
if (this.userdata === undefined) {
console.log(data);
//this.userdata = new BehaviorSubject<any[]>(data);
console.log(this.userdata);
} else {
console.log(this.userdata);
this.userdata.next(data);
}
}
}
My Dashbord Component:
@Component({
selector: 'dashboard',
styleUrls: ['./dashboard.scss'],
templateUrl: './dashboard.html'
})
export class Dashboard {
public isLoggedIn: boolean;
public curr_user: object;
constructor(private _appGlobals: AppGlobals, private _user: UserProfileService) {
this._appGlobals.isUserLoggedIn.subscribe(value => this.isLoggedIn = value);
// this.curr_user = _user.userdata;
}
ngAfterContentInit() {
console.log("this executes first");
this._user.userdata.subscribe(value => {
this.curr_user = value;
console.log(value);
});
}
set_new_data() {
let obj = {
name: "test",
age: 45
};
this._user.userdata.next(obj);
}
}
My Console output, (shows empty object: {}, expected the userdata)
UserProfileService
? Why do you have this line commented out in you code//this.userdata = new BehaviorSubject<any[]>(data);
. It's safe to remove it completely. There shouldn't be any need to assign a new instance to it. This would invalidate all subscriptions. – Günter Zöchbauerthis._userdata.next(someInitialValue);
– Günter ZöchbauerloadChildren: 'app/pages/login/login.module#LoginModule'
– johanUserProfileService
around. Try to only provide the service inAppModule
and try again if you get the desired behavior. You can implementforRoot()
and useforRoot()
to import lazy loaded modules to ensure only a single service instance is created. angular.io/guide/ngmodule-faq#what-is-the-forroot-method – Günter Zöchbauer