0

I have the following ProfileService:

export class ProfileService {
  private user: BehaviorSubject<User> = new BehaviorSubject<User>(null);

  constructor(private userService: UserService) { 
    this.userService.getUser(1)
      .pipe(map((payload: Payload<Result>) => payload.result))
      .subscribe((User: user): this.user.next(user));
  }

  public getUser() : Observable<User> {
    return this.user.asObservable();
  } 
}

On a few components I inject the AuthorizationService and call the authorize method:

export class AuthorizationService {

  user$: Observable<User>;

  constructor(private profileService: ProfileService) { 
    this.user$ = this.profileService.getUser();
  }

  authorize(policy: Policy, data: any) : Observable<boolean> {

    this.user$.subscribe(x => console.log(x)); // PROBLEM HERE
    // Remaing code

  }

}

Problem
The first time I use console.log in authorize I always get null for user$

Any idea why?

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • Sounds like you might have a race condition issue; assuming `getUser()` is async, by the time you `console.log`, the call hasn't yet finished, which is probably why you have a null value – Derek Pollard Sep 16 '20 at 18:05

1 Answers1

3

You are using a BehviourSubject which you initialize with null which will then always be the first emission. If you want to prevent that, use a regular Subject instead:

private user = new Subject<User>();

This will emit whenever next is being called on it.

Or ReplaySubject

private user = new ReplaySubject<User>(1);

by initializing it with 1 it will store the last value and emit that when subscribed to.

Note: with both of these you will lose the ability to access .value and .getValue()

mchl18
  • 2,119
  • 12
  • 20