angularrxjsngrx-component-store

RxJs - How to properly handle an observable if its empty before it is used for a service?


I am capturing the id$ from the route and I want to check that the observable is not empty, before I pass it to a service when it is needed. Is there a RxJs approach to check if it is not empty, without subscribing?

    id$: Observable<string | null>;        

    constructor(
        activatedRoute: ActivatedRoute,
        private store: Store
    ) {
        this.id$ = activatedRoute.parent!.paramMap.pipe(
            map((p) => p.get('id')),
        );

        combineLatest([this.id$]).subscribe((p) => {
            let id = 0;

            if (p && +p) {
                id = +p;
                this.store.load({ id });
            } else {
                this.store.setStoreStatusTo('error'); // my current way to handle the error
            }
            
        });
    }

    // this is where I want to be sure that id$ is not empty
    sendToService = () => this.store.sendToService(this.id$); 

Solution

  • I would suspect filter may do the trick (https://rxjs.dev/api/operators/filter)

    so in your case it would probably be

    this.id$.pipe(
    filter(x => x !== undefined)) //or whatever null checking you need to do
    .subscribe(x => {...})