Home > Blockchain >  Why doesn't my observable in Angular work as expected?
Why doesn't my observable in Angular work as expected?

Time:05-17

I have the following observable, which I DO subscribe to. Yet it does not fire on page load. Can you please help. I get no console errors, by the way

  maxBackDateTrigger$ = new Subject<void>();
  isGettingMaxBackDate$ = new Subject<boolean>();

  setMaxBackDate$ = this.maxBackDateTrigger$.pipe(
    tap(() => this.$spService.clientProfile$),
    withLatestFrom(this.$spService.clientProfile$),
    map(([trigger, client]) => {
      this.maxBackdate = client.caseStart;
    })
  );

CodePudding user response:

Subject's do not have a starting value. So when you do maxBackDateTrigger$ = new Subject<void>(); it would not yeild on load (as designed)

The fix is to change it to a BehaviorSubject as:

A variant of Subject that requires an initial value and emits its current value whenever it is subscribed to.

changing it to the following should get you going:

maxBackDateTrigger$ = new BehaviorSubject<void>(null);

CodePudding user response:

Void subjects have nothing to emit. So unlike value subjects that emit the current value they have once they are subscribed to, void subjects just don't emit anything and hence your trigger doesn't take place.

So because you have a void subject, you would need to explicitly call next on page load to fire the subject. That is, after setMaxBackDate$, (or preferably in ngOnInit),

maxBackDateTrigger$.next();
  • Related