Your service could look something like this...
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable()
export class AuthenticationService {
private _user_data: BehaviorSubject<any> = new BehaviorSubject<any>(null);
constructor() {
this._restoreUser()
}
get user_data(): Observable<any> {
return this._user_data.asObservable();
}
private _restoreUser(): void {
let user: any;
// use any code to restore user from cache and assign it to the scoped user variable
this._user_data.next(user);
}
}
And in your home component...
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
export class HomeComponent implements OnInit, OnDestroy {
public userdata: any;
private _userdataSub: Subscription;
constructor(private authenticationService: AuthenticationService) { }
ngOnInit() {
this._userdataSub = this.authenticationService.user_data.subscribe((userdata) => {
this.userdata = userdata;
});
}
ngOnDestroy() {
this._userdataSub.unsubscribe();
}
}
?(elvis operator) does is ensure that the object exists, then it'll go for the sub object. It's important to see what's in your object as it may not have the right field, or yourauthenticationServicemay not be returning anything.authenticationService?