|
@Injectable() |
|
export class AuthService { |
|
private user: BehaviorSubject<User> = new BehaviorSubject<User>(null); |
|
|
|
login(username: string, password: string) { |
|
let user = new User("username", "email"); |
|
this.user.next(user); |
|
} |
|
|
|
/** |
|
* @returns observable with current logged in user or null if user is not logged in. |
|
*/ |
|
getUser(): Observable<User> { |
|
return this.user.asObservable(); |
|
} |
|
} |
|
|
|
@Component({ |
|
moduleId: module.id, |
|
selector: 'navbar', |
|
templateUrl: 'navbar.component.html' |
|
}) |
|
export class NavbarComponent implements OnInit { |
|
|
|
private user: Observable<User>; |
|
|
|
constructor(private _authService: AuthService) { |
|
this.user = _authService.getUser(); |
|
} |
|
} |
|
|
|
@Component({ |
|
moduleId: module.id, |
|
selector: 'user-profile', |
|
templateUrl: 'profile.component.html' |
|
}) |
|
export class ProfileComponent { |
|
private user: Observable<User>; |
|
|
|
constructor( |
|
private _authService: AuthService, |
|
private _profileService: ProfileService) { |
|
this.user = _authService.getUser(); |
|
} |
|
} |
|
|
|
both profile.component.html and navbar.component.html are using snippets like: |
|
{{(user | async)?.username}} |
|
{{(user | async)?.email}} |
|
{{(user | async)?.otherField}} |
|
|
|
If I change the method to: |
|
getUser(): Observable<User> { |
|
return this.user.asObservable().share(); |
|
} |
|
|
|
Then behavior is very strange, one component doesn't see the values at all, second sees the username but email is empty, etc.. |
|
I think share makes sense only if you really subscribe to it, but in your example we simply assign observable to field |
|
and then use through (data | async) which may cause these side effects. |
|
|