Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour subject initial value null?

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?

like image 983
None Avatar asked Jun 22 '17 07:06

None


People also ask

How do I get my ReplaySubject value?

subscribe(num => console. log('last: ' + num)); If you don't want your stream to end, but you do want subscribers to receive the last value emitted before subscription, consider reaching for BehaviorSubject , which was designed for this use case.

How do I get BehaviorSubject value?

So the only solution that I found to get the value of a BehaviorSubject was: let value; myBehaviorSubject. take(1). subscribe( (e) => value = e );

What is the difference between subject and BehaviorSubject?

A BehaviorSubject holds one value (so we actually need to initialize a default value). When it is subscribed it emits that value immediately. A Subject on the other hand, does not hold a value.


1 Answers

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); 
like image 105
Estus Flask Avatar answered Oct 07 '22 16:10

Estus Flask