Home > Mobile >  Angular Observable best approach for condition
Angular Observable best approach for condition

Time:12-25

Assuming I'd like to be notified and consume an async pipe when it's populated What would be the best approach for that.

 this.some_page = this.api.getReportPage();

        this.route.queryParams.subscribe(p => {
            this.checkIdQueryParam = p.checkId;
            /**
             * variable some_page is consumed via async pipe in the template and i'd like to be notified when it's consumed 
             * (or change the entire design if needed, e.g - not use async or something
             */

    });

The purpose is that when there's a query param , i'd like to invoke some action, but it depends on the some_page to be populated.

CodePudding user response:

You can use switchmap of rxjs

this.some_page = this.route.queryParams
        .pipe(switchMap((p) => {
          if (p.checkId) {
         
            return this.api.getReportPage();
          }
          return of([]);
        }))

CodePudding user response:

What you're trying to do is called a "Side Effect" which should always be done by the tap() operator. It should be something like this:

this.some_page$ = this.route.queryParams
  .pipe(switchMap((param) => {
      const checkId: string = param.checkId ?? '';
      return !checkId ? of([]) : this.api.getReportPage().pipe(
        tap((getReportRes) => {
          //invoke Actions
        })
      );
  }))

  • Related