Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

BehaivorSubject return null

I have this problem, I need the behaivorSubject not to return the value when it is null, since the result is grabbed by a component made by third parties and if this is null it throws me an error.

It should return the same only when I get the response from the server, I leave my code here:

  getCarList(params): Observable<CarListGrid> {
    if (this.carListSubject$ === undefined) {
      this.carListSubject$ = new BehaviorSubject<CarListGrid>(null);
      this.refetchCarList(params);
    }
    return this.carListSubject$.asObservable();
  }

  refetchCarList(gridParams) {
    const subscription = this.http.post<CarListGrid>(this.baseUrl + 'GetCar', {gridParams} ,httpOptions).pipe(map(data => this.setDefaultValuesToCar(data))).subscribe(
      (response) => {

        this.carListSubject$.next(response);
        subscription.unsubscribe();
      });
  }

Is there any way to prevent the subject from responding with a value when it is null? Or else, how can I give this code another way to help me with that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

You could filter those nulls out, like this:

getCarList(params): Observable<CarListGrid> {
  if (this.carListSubject$ === undefined) {
    this.carListSubject$ = new BehaviorSubject<CarListGrid>(null);
    this.refetchCarList(params);
  }
  return this.carListSubject$
    .asObservable()
    .pipe(filter((value) => value !== null));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading