rxjs/operators#pluck TypeScript Examples

The following examples show how to use rxjs/operators#pluck. 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: epics.ts    From anthem with Apache License 2.0 6 votes vote down vote up
setActiveChartTabEpic: EpicSignature = (action$, state$, deps) => {
  return action$.pipe(
    filter(isActionOf(Actions.onRouteChange)),
    pluck("payload"),
    pluck("pathname"),
    filter(pathname => onChartTab(pathname)),
    map(pathname => {
      const { network } = state$.value.ledger.ledger;
      const { activeChartTab } = state$.value.app.app;
      const tab = pathname.split("/")[2];
      const validTab = isChartTabValidForNetwork(tab, network);

      if (validTab && validTab !== activeChartTab) {
        return Actions.setActiveChartTab(validTab);
      } else {
        return Actions.empty("No need to update the active chart tab...");
      }
    }),
  );
}
Example #2
Source File: sign-request.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
networkPassphraseToUse$ = this.connectQuery.networkPassphraseToUse$
    .pipe(switchMap(network => {
      if (!!network) {
        return of(network);
      }

      return this.horizonApisQuery.getSelectedHorizonApi$
        .pipe(pluck('networkPassphrase'));
    }));
Example #3
Source File: volume-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Makes request for liquidity providing rewards.
   * @return Observable LpReward[].
   */
  public fetchLpRewards(): Observable<LpReward[]> {
    return this.httpService
      .get<{ rewardsByDays: LpReward[] }>('total_values/stats/lp-rewards')
      .pipe(pluck('rewardsByDays'));
  }
Example #4
Source File: user.structure.ts    From App with MIT License 6 votes vote down vote up
getAuditEntries(): Observable<AuditLogEntry[]> {
		return this.dataOnce().pipe(
			switchMap(data => data?.audit_entries ?? []),
			pluck('id'),
			map(entryID => this.dataService.get('audit', { id: entryID } )),
			map(a => a[0]),
			filter(e => !!e),
			toArray()
		);
	}
Example #5
Source File: customOperators.ts    From webapp with MIT License 6 votes vote down vote up
rankPriority =
  () =>
  <T>(source: Observable<RankItem<T>>) =>
    source.pipe(
      scan(
        (lastEmitted, value) => {
          const betterPriority =
            !lastEmitted.emittedOnce ||
            value.priority < lastEmitted.lastPriority;

          return betterPriority
            ? {
                emit: true,
                emittedOnce: true,
                lastPriority: value.priority,
                toEmit: value.data
              }
            : {
                emit: false,
                emittedOnce: true,
                lastPriority: lastEmitted.lastPriority,
                toEmit: undefined
              };
        },
        {
          emit: false,
          emittedOnce: false,
          lastPriority: 0,
          toEmit: undefined
        } as {
          emit: boolean;
          emittedOnce: boolean;
          lastPriority: number;
          toEmit: undefined | T;
        }
      ),
      filter(emission => emission.emit),
      pluck("toEmit")
    ) as Observable<T>
Example #6
Source File: distinct-unique-key.operator.ts    From etherspot-sdk with MIT License 6 votes vote down vote up
/**
 * @ignore
 */
export function distinctUniqueKey<T, K extends keyof T>(key: K): OperatorFunction<T, T[K]> {
  return (input$) =>
    input$.pipe(
      map((value) => {
        return (value ? value : { [key]: null }) as T;
      }),
      distinctUntilKeyChanged(key, deepCompare),
      pluck(key),
    );
}
Example #7
Source File: bootstrap.service.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
uiConfReady(uiIdentifier: string): Observable<any> {
    if (!this.uiConfigurations[uiIdentifier]) {
      this.uiConfigurations = {
        ...this.uiConfigurations,
        [uiIdentifier]: this.uiService.getUiConfiguration(uiIdentifier).pipe(
          pluck('configuration'),
          map((configString) => this.buildConfig(configString)),
          catchError(() => {
            this.logService.warn(
              `Error during UI configuration loading: ${uiIdentifier}. Using default.`
            )
            return of(this.buildConfig(DEFAULT_UI_CONFIG))
          }),
          shareReplay()
        ),
      }
    }
    return this.uiConfigurations[uiIdentifier]
  }
Example #8
Source File: add.ts    From ble with Apache License 2.0 6 votes vote down vote up
addVertexOrEntity: Epic = (action$, { store }) => {
	return action$.pipe(
		// we listen specifically on the background because when a user clicks another object they
		// probably expect to select it
		ofType('backgroundPointerDown'),
		pluck('ev', 'data'),
		filter((data) => data.button === 0 || data.pointerType === 'touch'),
		map(({ global }) => store.editor.screenToWorld({
			x: global.x,
			y: global.y,
		})),
		map((posInWorld) => snapToGrid(posInWorld, store.editor.gridCellSize)),
		filter(() => store.editor.mode === EditorMode.addVertex || store.editor.mode === EditorMode.addBlock),
		mergeMap((posInWorld: IPoint) => {
			switch (store.editor.mode) {
				case EditorMode.addVertex:
					return of({
						type: 'addVertex',
						pos: posInWorld,
					});
				case EditorMode.addBlock:
					return of({
						type: 'createEntity',
						pos: posInWorld,
					});
			}

			return empty();
		}),
	);
}
Example #9
Source File: details.page.ts    From capture-lite with GNU General Public License v3.0 6 votes vote down vote up
private readonly fromPostCaptures$ =
    this.diaBackendAssetRepository.postCaptures$.pipe(
      pluck('results'),
      map(postCaptures =>
        postCaptures.map(
          p =>
            new DetailedCapture(
              p,
              this.mediaStore,
              this.diaBackendAssetRepository,
              this.errorService,
              this.diaBackendAuthService,
              this.translocoService,
              this.diaBackendWorkflowService
            )
        )
      )
    );
Example #10
Source File: moment-repository.service.ts    From ionic-pwa-example-moment with MIT License 6 votes vote down vote up
private readonly collection$: Observable<
    RxCollection<MemontIndex>
  > = this.database.main$.pipe(
    concatMap(database =>
      database.addCollections({
        [COLLECTION_NAME]: { schema },
      })
    ),
    pluck(COLLECTION_NAME),
    shareReplay({ bufferSize: 1, refCount: true })
  );
Example #11
Source File: comments.web.service.ts    From sba-angular with MIT License 6 votes vote down vote up
/**
     * Return the list of comments for a given document
     * @param docid 
     * @returns 
     */
    getComments(docid: string): Observable<Comment[]> {
        return this.httpClient.post<{comments: Comment[]}>(
            this.makeUrl(this.endpoint), {docid, action: 'read'}
        ).pipe(pluck('comments'));
    }
Example #12
Source File: project-navigation.component.ts    From taiga-front-next with GNU Affero General Public License v3.0 6 votes vote down vote up
public ngOnInit() {
    this.collapsed = (localStorage.getItem('projectnav-collapsed') === 'true');
    this.section = this.getActiveSection();

    // LEGACY
    this.milestoneId$ = this.legacyService.legacyState
    .pipe(
      pluck('detailObj'),
      map((obj) => {
        return obj?.milestone;
      })
    );

    if (this.section === 'backlog') {
      this.scrumVisible = (localStorage.getItem('projectnav-scrum') === 'true');
    }
  }
Example #13
Source File: account-list.component.ts    From distributed-compliance-ledger with Apache License 2.0 6 votes vote down vote up
ngOnInit() {
    const source = this.accountService.getAccountHeaders().pipe(
      share()
    );

    this.total$ = source.pipe(
      pluck('total')
    );

    this.items$ = source.pipe(
      pluck('items')
    );
  }
Example #14
Source File: epics.ts    From anthem with Apache License 2.0 5 votes vote down vote up
syncAddressToUrlEpic: EpicSignature = (action$, state$, deps) => {
  return action$.pipe(
    filter(
      isActionOf([Actions.setAddressSuccess, Actions.connectLedgerSuccess]),
    ),
    filter(() => {
      const { location } = deps.router;
      return onPageWhichIncludesAddressParam(location.pathname);
    }),
    pluck("payload"),
    tap(({ network }) => {
      const { address } = state$.value.ledger.ledger;
      const { transactionsPage } = state$.value.transaction;
      const { location } = deps.router;
      const { pathname } = location;
      const tab = pathname.split("/")[2];
      const onChartView = onChartTab(tab);
      const onValidChartTab = isChartTabValidForNetwork(tab, network);

      const search =
        transactionsPage > 1
          ? `?address=${address}&page=${transactionsPage}`
          : `?address=${address}`;

      if (search !== location.search) {
        deps.router.replace({ search });
      }

      const name = network.name.toLowerCase();
      const onDifferentNetwork = !pathname.includes(name);

      if ((!onValidChartTab && onChartView) || onDifferentNetwork) {
        deps.router.replace({
          search,
          pathname: `/${name}/total`,
        });
      }
    }),
    ignoreElements(),
  );
}
Example #15
Source File: background.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
connectHandler$ = this.runtimeEvent$.asObservable()
    .pipe(filter(message => message.event === XBULL_CONNECT_BACKGROUND))
    .pipe(pluck('payload'))
    .pipe(switchMap(payload => this.connectHandler(payload as IConnectRequestPayload)));
Example #16
Source File: stake-button-container.component.ts    From rubic-app with GNU General Public License v3.0 5 votes vote down vote up
public readonly isBridgeTokenSelected$ = this.stakingService.selectedToken$.pipe(
    pluck('blockchain'),
    map(blockchain => blockchain !== BLOCKCHAIN_NAME.BINANCE_SMART_CHAIN)
  );
Example #17
Source File: auth.interceptor.ts    From auth0-angular with MIT License 5 votes vote down vote up
intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const config = this.configFactory.get();
    if (!config.httpInterceptor?.allowedList) {
      return next.handle(req);
    }

    return this.findMatchingRoute(req, config.httpInterceptor).pipe(
      concatMap((route) =>
        iif(
          // Check if a route was matched
          () => route !== null,
          // If we have a matching route, call getTokenSilently and attach the token to the
          // outgoing request
          of(route).pipe(
            pluck('tokenOptions'),
            concatMap<GetTokenSilentlyOptions, Observable<string>>(
              (options) => {
                return this.getAccessTokenSilently(options).pipe(
                  catchError((err) => {
                    if (this.allowAnonymous(route, err)) {
                      return of('');
                    }

                    this.authState.setError(err);
                    return throwError(err);
                  })
                );
              }
            ),
            switchMap((token: string) => {
              // Clone the request and attach the bearer token
              const clone = token
                ? req.clone({
                    headers: req.headers.set(
                      'Authorization',
                      `Bearer ${token}`
                    ),
                  })
                : req;

              return next.handle(clone);
            })
          ),
          // If the URI being called was not found in our httpInterceptor config, simply
          // pass the request through without attaching a token
          next.handle(req)
        )
      )
    );
  }
Example #18
Source File: contracts.ts    From webapp with MIT License 5 votes vote down vote up
exchangeProxy$ = zeroXContracts$.pipe(
  pluck("exchangeProxy"),
  shareReplay(1)
)
Example #19
Source File: search-summary.component.ts    From geonetwork-ui with GNU General Public License v2.0 5 votes vote down vote up
publisher$ = this.searchFacade.searchFilters$.pipe(
    pluck('Org'),
    map((orgState) => orgState && Object.keys(orgState)[0])
  )
Example #20
Source File: select.ts    From ble with Apache License 2.0 5 votes vote down vote up
entityMove: Epic = (action$, { store }) => {
	return action$.pipe (
		ofType('entityPointerDown'),
		filter(() => store.editor.mode === EditorMode.select),
		// middle click is panning only
		filter(({ ev }) => !(ev.data.pointerType === 'mouse' && ev.data.button === 1)),
		// it's important to use global and not original event
		// because TouchEvents don't have clientX
		pluck('ev', 'data', 'global'),
		// we copy the relevant data because react pools events
		map(({ x, y }) => ({
			x: x + store.editor.renderZone.x,
			y: y + store.editor.renderZone.y,
		})),
		tap(() => {
			store.undoManager.startGroup();
		}),
		switchMap(({ x, y }) => fromEvent<PointerEvent>(document, 'pointermove').pipe(
			map(({ clientX, clientY }) => new Vector(clientX, clientY)),
			startWith(new Vector(x, y)),
			pairwise(),
			map(([prev, curr]) => curr.clone().sub(prev)),
			filter((vec) => vec.len2() !== 0),
			map((vec) => vec.scale(1/store.editor.scale)),
			scan((acc, delta) => {
				const totalDelta = acc.clone().add(delta);

				const displacement = snapBoxToGrid(
					new Box(
						store.editor.selectionAsAabb.pos.clone().add(totalDelta),
						store.editor.selectionAsAabb.w,
						store.editor.selectionAsAabb.h,
					),
					store.editor.gridCellSize,
				);

				store.editor.selection.forEach((entity: IEntity) => {
					entity.params.move(totalDelta.x + displacement.x, totalDelta.y + displacement.y);
				});

				return displacement.reverse();
			}, new Vector(0, 0)),
			takeUntil(fromEvent(document, 'pointerup').pipe(
				tap(() => {
					store.undoManager.stopGroup();
				}),
			)),
		)),
		ignoreElements(),
	);
}
Example #21
Source File: contacts.page.ts    From capture-lite with GNU General Public License v3.0 5 votes vote down vote up
readonly contacts$ = this.diaBackendContactRepository.all$.pipe(
    pluck('results'),
    catchError((err: unknown) => this.errorService.toastError$(err)),
    shareReplay({ bufferSize: 1, refCount: true })
  );