rxjs#tap TypeScript Examples

The following examples show how to use rxjs#tap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: wowup-protocol.service.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
public initialize() {
    this._electronService.customProtocol$
      .pipe(
        tap((prt) => console.log("WowUpProtocolService", prt)),
        filter((prt) => getProtocol(prt) === APP_PROTOCOL_NAME && this.isInstallAction(prt)),
        switchMap((prt) => this.onInstallProtocol(prt)),
        catchError((e) => {
          console.error(e);
          return of(undefined);
        })
      )
      .subscribe();
  }
Example #2
Source File: autocomplete.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
ngAfterContentInit() {
    this.hasVisibleSuggestion$ = this.suggestions.changes.pipe(
      startWith(this.suggestions),
      switchMap((suggestions: QueryList<SuggestionComponent>) =>
        suggestions.length > 0
          ? combineLatest(suggestions.map(suggestion => suggestion.visible$))
          : of([] as boolean[]),
      ),
      map(visible => visible.some(Boolean)),
      withLatestFrom(this.directive$$),
      map(([hasVisibleSuggestion, directive]) => {
        if (hasVisibleSuggestion && directive.defaultFirstSuggestion) {
          directive.autoFocusFirstSuggestion();
        }
        return hasVisibleSuggestion;
      }),
      distinctUntilChanged(),
      debounceTime(0),
      tap(() => this.cdr.markForCheck()),
      publishRef(),
    );

    this.hasContent$ = combineLatest([
      this.hasVisibleSuggestion$,
      this.placeholder.changes.pipe(
        startWith(this.placeholder),
        map(
          (list: QueryList<AutocompletePlaceholderComponent>) => !!list.length,
        ),
      ),
    ]).pipe(
      map(
        ([hasVisibleSuggestion, hasPlaceholder]) =>
          hasVisibleSuggestion || hasPlaceholder,
      ),
    );
  }
Example #3
Source File: suggestion.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
constructor(
    private readonly cdr: ChangeDetectorRef,
    @Inject(forwardRef(() => AutocompleteComponent))
    autocomplete: any, // FIXME: workaround temporarily
  ) {
    this.autocomplete = autocomplete;
    this.selected$ = combineLatest([
      this.autocomplete.directive$$.pipe(
        switchMap(directive => directive.inputValue$),
      ),
      this.value$$,
    ]).pipe(
      map(([inputValue, selfValue]) => inputValue === selfValue),
      tap(selected => {
        this.selected = selected;
      }),
      publishRef(),
    );
    this.visible$ = combineLatest([
      this.autocomplete.directive$$.pipe(
        switchMap(directive => directive.filterFn$),
      ),
      this.autocomplete.directive$$.pipe(
        switchMap(directive => directive.inputValue$),
      ),
      this.value$$,
    ]).pipe(
      map(([filterFn, filterString, suggestion]) =>
        filterFn(filterString, suggestion),
      ),
      tap(visible => {
        this.visible = visible;
      }),
      publishRef(),
    );
  }
Example #4
Source File: fixed-size-table-virtual-scroll.directive.ts    From alauda-ui with MIT License 6 votes vote down vote up
ngAfterContentInit() {
    this.scrollStrategy.stickyChange
      .pipe(
        filter(() => this.isStickyEnabled()),
        tap(() => {
          if (!this.stickyPositions) {
            this.initStickyPositions();
          }
        }),
        takeUntil(this.onDestroy$),
      )
      .subscribe(stickyOffset => {
        this.setSticky(stickyOffset);
      });
    combineLatest([this.scrollStrategy.renderedRangeStream, this._dataSource$$])
      .pipe(
        map(([{ start, end }, dataSource]) =>
          typeof start !== 'number' || typeof end !== 'number'
            ? dataSource
            : dataSource?.slice(start, end),
        ),
        takeUntil(this.onDestroy$),
      )
      .subscribe(data => {
        this.table.dataSource = data;
      });
  }
Example #5
Source File: multi-select.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
override ngAfterViewInit() {
    super.ngAfterViewInit();
    this.selectAllStatus$ = combineLatest([
      this.allOptions$,
      this.filterString$,
    ]).pipe(
      switchMap(([allOptions]) =>
        combineLatest([
          ...(allOptions ?? [])
            .filter(({ visible, disabled }) => visible && !disabled)
            .map(({ selected$ }) => selected$),
        ]),
      ),
      map(statuses => {
        const selected = statuses.filter(Boolean);
        return selected.length === 0
          ? SelectAllStatus.Empty
          : selected.length !== statuses.length
          ? SelectAllStatus.Indeterminate
          : SelectAllStatus.Checked;
      }),
      startWith(SelectAllStatus.Empty),
      tap(selectAllStatus => (this.selectAllStatus = selectAllStatus)),
      publishRef(),
    );
    this.hasEnabledOptions$ = combineLatest([
      this.allOptions$,
      this.filterString$,
    ]).pipe(
      map(
        ([allOptions]) =>
          !!allOptions.filter(({ visible, disabled }) => visible && !disabled)
            .length,
      ),
    );
  }
Example #6
Source File: tree-select.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
ngAfterViewInit() {
    const hasVisibleChildNodes$ = this.childNodes.changes.pipe(
      startWith(this.childNodes),
      switchMap((nodes: QueryList<TreeNodeComponent<T>>) =>
        nodes.length > 0
          ? combineLatest(nodes.map(node => node.visible$))
          : of([false]),
      ),
      map(visible => visible.some(Boolean)),
      tap(hasVisibleChildren => (this.isLeaf = !hasVisibleChildren)),
    );
    this.visible$ = combineLatest([
      this.selfVisible$,
      hasVisibleChildNodes$,
    ]).pipe(
      map(visible => visible.some(Boolean)),
      publishRef(),
    );

    this.visible$.pipe(takeUntil(this.destroy$$)).subscribe(visible => {
      this.visible = visible;
      this.cdr.markForCheck();
    });
    this.selected$.pipe(takeUntil(this.destroy$$)).subscribe(selected => {
      this.selected = selected;
      this.cdr.markForCheck();
    });

    if (this.selected) {
      requestAnimationFrame(() => {
        this.scrollToNode(this);
      });
    }
  }
Example #7
Source File: tree-select.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
constructor(
    select: TreeSelectComponent<T>,
    private readonly cdr: ChangeDetectorRef,
  ) {
    this.select = select;
    this.selected$ = combineLatest([
      this.select.model$,
      this.nodeData$$.pipe(map(data => data.value)),
    ]).pipe(
      map(
        ([selectValue, selfValue]) =>
          selectValue &&
          this.select.trackFn(selectValue) === this.select.trackFn(selfValue),
      ),
      tap(selected => {
        this.selected = selected;
      }),
      publishRef(),
    );
    this.selfVisible$ = combineLatest([
      this.select.filterString$,
      this.nodeData$$,
    ]).pipe(
      map(([filterString, nodeData]) =>
        this.select.filterFn(filterString, nodeData),
      ),
      publishRef(),
    );
  }
Example #8
Source File: auth.ts    From bext with MIT License 6 votes vote down vote up
accessToken$
  .pipe(
    map((auth) => (auth ? new Octokit({ auth }) : null)),
    tap((octokit) =>
      octokit?.hook.error('request', (error: any) => {
        if (error?.status === 401) {
          notifications$.getValue()?.notify({
            status: 'warning',
            message: '登录失败,请重新登录',
          });
          accessToken$.next(undefined);
        }
        throw error;
      }),
    ),
  )
  .subscribe(octokit$);
Example #9
Source File: datadog.interceptor.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
intercept(
    context: ExecutionContext,
    next: CallHandler<unknown>,
  ): Observable<unknown> {
    const start = new Date().getTime();
    return next.handle().pipe(
      tap(() => {
        const duration = new Date().getTime() - start;

        const request = context.switchToHttp().getRequest<Request>();
        if (!request) {
          return;
        }

        this.datadogService.timing('requests.success', duration, {
          method: request.method,
          path: request.path,
        });
      }),
      catchError((error: Error) => {
        let method = 'no-method';
        let path = 'no-path';

        const request = context.switchToHttp().getRequest<Request>();
        if (request) {
          method = request.method;
          path = request.path;
        }

        this.datadogService.increment('requests.error', 1, {
          method,
          path,
          type: error.constructor.name,
        });

        return throwError(() => error);
      }),
    );
  }
Example #10
Source File: anchor.component.ts    From alauda-ui with MIT License 5 votes vote down vote up
ngAfterViewInit() {
    const { injectId, containerEl, scrollableEl } = this.parent;
    const pageContentEl = containerEl.closest('.aui-page__content');
    const paddingTop = pageContentEl
      ? +getComputedStyle(pageContentEl).paddingTop.slice(0, -2)
      : 0;
    fromEvent(scrollableEl, 'scroll')
      .pipe(
        debounceTime(100),
        switchMap(() => {
          const { scrollTop } =
            scrollableEl === window
              ? document.documentElement
              : (scrollableEl as HTMLElement);
          const activedItem =
            this.items.find(
              ({ target }) =>
                target.offsetTop +
                  target.offsetHeight / 2 +
                  ((scrollableEl === window &&
                    (target.offsetParent as HTMLElement)?.offsetTop) ||
                    0) >
                scrollTop + paddingTop,
            ) || last(this.items);
          return activedItem ? of(activedItem) : EMPTY;
        }),
        tap(activedItem => {
          if (activedItem.id) {
            this.activeId = activedItem.id;
            this.cdr.markForCheck();
          }
        }),
        debounceTime(100),
        tap(activedItem => {
          if (injectId && activedItem.id) {
            history.replaceState(
              null,
              null,
              location.pathname + location.search + '#' + activedItem.id,
            );
          }
        }),
        takeUntil(this.destroy$$),
      )
      .subscribe();
  }
Example #11
Source File: option.component.ts    From alauda-ui with MIT License 5 votes vote down vote up
constructor(
    private readonly cdr: ChangeDetectorRef,
    @Inject(forwardRef(() => BaseSelect))
    select: any, // FIXME: workaround temporarily
  ) {
    this.isMulti = select.isMulti;
    this.select = select;
    this.selected$ = combineLatest([this.select.values$, this.value$$]).pipe(
      map(([selectValue, selfValue]) =>
        selectValue
          ?.map(this.select.trackFn)
          .includes(this.select.trackFn(selfValue)),
      ),
      distinctUntilChanged(),
      tap(selected => {
        this.selected = selected;
      }),
      publishRef(),
    );
    this.size$ = this.select.size$.pipe(
      tap(size => {
        this.size = size;
      }),
    );
    this.visible$ = combineLatest([
      this.select.filterString$,
      combineLatest([this.label$, this.value$, this.labelContext$]).pipe(
        map(([label, value, labelContext]) => ({ label, value, labelContext })),
      ),
    ]).pipe(
      map(([filterString, option]) =>
        this.select.filterFn(filterString, option),
      ),
      distinctUntilChanged(),
      tap(visible => {
        this.visible = visible;
      }),
      publishRef(),
    );
  }
Example #12
Source File: toc-container.directive.ts    From alauda-ui with MIT License 5 votes vote down vote up
ngAfterContentInit() {
    const actived$ = this._scrollTop$
      .pipe(
        startWith(this.scrollTop),
        debounceTime(200),
        map(scrollTop =>
          this._contents.reduce(
            this.isScrollEnd
              ? this.getMaxContent.bind(this)
              : this.getMinContent(scrollTop),
          ),
        ),
        map(actived => actived.auiTocContent),
      )
      .pipe(
        tap(actived => {
          this._contents.forEach(content => {
            content.active = actived === content.auiTocContent;
          });
          this.cdr.detectChanges();
        }),
      );

    const scrollTween$ = this._scrollTo$.pipe(
      switchMap(name => {
        const target = this._contents.find(
          content => content.auiTocContent === name,
        );

        if (!target) {
          return EMPTY;
        }
        const destination = this.getOffsetTop(target.nativeElement);

        const start = performance.now();
        const source = this.scrollTop;
        const duration = 500;

        return of(0).pipe(
          observeOn(animationFrameScheduler),
          repeat(),
          map(() => (performance.now() - start) / duration),
          takeWhile(t => t < 1),
          endWith(1),
          map(t => t * t * t),
          map(t => source * (1 - t) + destination * t),
        );
      }),
      takeUntil(this._onDestroy$),
    );

    this._subs.push(
      actived$.subscribe(this.activedChange),
      scrollTween$.subscribe(tweenValue => {
        this.scrollTop = tweenValue;
      }),
    );
  }
Example #13
Source File: wrapped-control-superclass.ts    From s-libs with MIT License 5 votes vote down vote up
#handleError<T>(): MonoTypeOperatorFunction<T> {
    return flow(
      tap<T>({ error: bindKey(this.#errorHandler, 'handleError') }),
      retry(),
    );
  }