Behaviour subject initial value null?

None picture None · Jun 22, 2017 · Viewed 49.3k times · Source
private customer: Subject<Object> = new BehaviorSubject<Object>(null);

setCustomer(id, accountClassCode) {
    this.customer.next({'id': id, 'accountClassCode': accountClassCode});
}

getCustomer() {
    return this.customer.asObservable();
}

I'm using this part of code but I'm getting an error that can not find id of null. Is there any solution to get initial value that is not null?

Answer

Estus Flask picture Estus Flask · Jun 22, 2017

The purpose of BehaviorSubject is to provide initial value. It can be null or anything else. If no valid initial value can be provided (when user id isn't known yet), it shouldn't be used.

ReplaySubject(1) provides a similar behaviour (emits last value on subscription) but doesn't have initial value until it is set with next.

It likely should be

private customer: Subject<Object> = new ReplaySubject<Object>(1);