Skip to content

Instantly share code, notes, and snippets.

@VadimKirilchuk
Created February 26, 2017 20:48
Show Gist options
  • Save VadimKirilchuk/12c4c7ebd86cb9743794bd5447f834b2 to your computer and use it in GitHub Desktop.
Save VadimKirilchuk/12c4c7ebd86cb9743794bd5447f834b2 to your computer and use it in GitHub Desktop.
Observable.share() issue
@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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment