Miguel Moura
Miguel Moura

Reputation: 39364

First value after subscribing observable is always null

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?

Upvotes: 0

Views: 2128

Answers (1)

mchl18
mchl18

Reputation: 2336

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()

Upvotes: 3

Related Questions