rxjs/operators#first TypeScript Examples

The following examples show how to use rxjs/operators#first. 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: spec.util.spec.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 7 votes vote down vote up
/**
 * Waits until the given number of subscribers are subscribed to the given topic, or throws an error otherwise.
 */
export async function waitUntilSubscriberCount(topic: string, expectedCount: number): Promise<void> {
  return new Promise<void>((resolve, reject) => {
    Beans.get(MessageClient).subscriberCount$(topic)
      .pipe(first(count => count === expectedCount))
      .subscribe({
        error: reject,
        complete: resolve,
      });
  });
}
Example #2
Source File: utils.ts    From gnosis.1inch.exchange with MIT License 6 votes vote down vote up
protected _triggerProviderIfRequired() {
    const now = this._getNow();
    if ((now - this.lastProviderTrigger) > this.windowTime) {
      // Data considered stale, provider triggering required...
      this.lastProviderTrigger = now;
      this.providerCallback().pipe(first()).subscribe((t: T) => this.next(t));
    }
  }
Example #3
Source File: bridge-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Gets token price.
   * @param bridgeTokenPair Object with info about pair of tokens.
   * @return number Token price.
   */
  private getTokenPrice(bridgeTokenPair: BridgeTokenPair): Observable<number> {
    return this.tokensService.tokens$.pipe(
      first(),
      map(backendTokens => {
        const prices = BLOCKCHAIN_NAMES.map(
          blockchain =>
            backendTokens.find(
              token =>
                bridgeTokenPair.tokenByBlockchain[blockchain]?.address.toLowerCase() ===
                token.address.toLowerCase()
            )?.price
        )
          .filter(it => it)
          .sort((a, b) => b - a);
        return prices[0] || 0;
      })
    );
  }
Example #4
Source File: tasks-queue.ts    From RcloneNg with MIT License 6 votes vote down vote up
/**
	 * @param t task
	 * @description Enqueue task
	 */
	public async AddTask<Tin, Tout>(t: Task<Tin, Tout>): Promise<CombErr<Tout>> {
		const result = new Subject<CombErr<Tout>>();
		const handler: TaskHandler<Tin, Tout> =
			typeof t.handler === 'string' ? TaskHandlerManager.find(t.handler) : t.handler;
		if (!handler) throw new Error(`handler id '${t.handler}' not registered in TaskHandlerManager`);
		return this.tasksQueue.add(async () => {
			handler(t.params, result);
			return result.pipe(first()).toPromise();
		});
	}
Example #5
Source File: feature-toggle.guard.ts    From canopy with Apache License 2.0 6 votes vote down vote up
isActive(route: Route | ActivatedRouteSnapshot) {
    return this.featureToggleService.toggles$.pipe(
      first(),
      map(configToggles => {
        const active = getDataPropertyValues(route, 'featureToggle')
          .map(t => {
            const value = configToggles[t];

            return value === undefined || value;
          })
          .reduce((acc, current) => acc && current, true);

        if (!active) {
          this.router.navigate([ '/' ], { queryParamsHandling: 'merge' });
        }

        return active;
      }),
    );
  }
Example #6
Source File: ion-media-cache.directive.ts    From ion-media-cache with MIT License 6 votes vote down vote up
constructor(
    private el: ElementRef,
    private file: File,
    private renderer: Renderer2,
    private platform: Platform,
    private webview: WebView) {
    this.tag = this.el;
    if (!window['IonMediaCache']) {
      window['IonMediaCache'] = {};
    }
    if (this.isMobile) {
      fromEvent(document, 'deviceready').pipe(first()).subscribe(res => {
        this.initCache();
      });
    } else {
      this.initCache();
    }
  }
Example #7
Source File: coupon.service.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
getLatestBalance() {
    const pool$ = this.getPoolCurrentBalance()
      .pipe(
        first(),
        tap(balance => this.poolBalance$.next(balance)),
      );
    const user$ = this.getUserCurrentBalance()
      .pipe(
        first(),
        tap(balance => this.userBalance$.next(balance)),
      );
    return forkJoin([pool$, user$]);
  }
Example #8
Source File: theme.service.ts    From nica-os with MIT License 6 votes vote down vote up
constructor(private store$: Store<AppState>) {
    this.subs.push(
      this.appSettings$.pipe(
        first(),
        map(({theme}) => {
          this.setTheme(theme);
        })
      ).subscribe()
    );
  }
Example #9
Source File: bom-license-exception-details.component.ts    From barista with Apache License 2.0 6 votes vote down vote up
onDelete() {
    if (confirm('Are you sure you want to delete this exception?')) {
      this.bomLicenseExceptionApiService
        .bomLicenseExceptionIdDelete(this.licenseException.id)
        .pipe(first())
        .subscribe(
          () => {
            this.showMessage(`Exception for License: ${this.licenseException.license.name} DELETED`);
            this.messageService.send(this.licenseException);
            this.dialogRef.close(true);
          },
          error => {
            this.dialog.open(AppDialogComponent, {
              data: { title: 'Error', message: JSON.stringify(error) },
            });
          },
        );
    }
  }
Example #10
Source File: user-detail.component.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
getUsersIfNecessary() {
    this.store
      .select(selectUsers)
      .pipe(first())
      .subscribe((users) => {
        if (users === null) {
          this.store.dispatch(getUsers());
        }
      });
  }
Example #11
Source File: context-service.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Resolves when subscribed to the given reply topic.
 *
 * @ignore
 */
function whenSubscribedToReplyTopic(topic: string): Promise<void> {
  return new Promise<void>((resolve, reject) => {
    Beans.get(MessageClient).subscriberCount$(topic)
      .pipe(first(count => count === 1))
      .subscribe({
        error: reject,
        complete: resolve,
      });
  });
}
Example #12
Source File: oauth.service.ts    From App with MIT License 6 votes vote down vote up
/**
	 * Navigate the currently opened popup to a url
	 *
	 * @param url The URL to redirect to
	 */
	navigateTo(url: string): void {
		if (!this.openedWindow) {
			this.windowOpened.pipe(first()).subscribe(win => win.location.href = url);
			return undefined;
		}

		this.openedWindow.location.href = url;
	}
Example #13
Source File: hero-select-dialog.component.ts    From colo-calc with Do What The F*ck You Want To Public License 6 votes vote down vote up
public heroSelected(character: Character): void {
    if (character.weapons?.length) {
      this.dialog.open(WeaponSelectDialogComponent, {
        //width: dialogWidth,
        data: {
          weapons: character.weapons
        }
      }).afterClosed().pipe(first()).subscribe((weapon: Weapon) => {
        const characterWithWeapon = this.characterService.getCharacterWithWeapon(character.id, weapon.id);
        this.handleExistingHero(characterWithWeapon);
        this.dialogRef.close(characterWithWeapon);
      })
    } else {
      this.handleExistingHero(character);
      this.dialogRef.close(character);
    }
  }
Example #14
Source File: wago-addon-provider.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
private ensureToken(timeoutMs = 10000): Observable<string> {
    if (this._circuitBreaker.isOpen()) {
      throw new Error("[wago] circuit breaker is open");
    }

    return this._apiTokenSrc.pipe(
      timeout(timeoutMs),
      first((token) => token !== ""),
      tap(() => console.log(`[wago] ensureToken`)),
      catchError(() => {
        console.error("[wago] no token received after timeout");
        return of("");
      })
    );
  }
Example #15
Source File: account-page.component.ts    From ReCapProject-Frontend with MIT License 6 votes vote down vote up
getUserDetailsFromStore() {
    this.authService.userDetail$.pipe(first()).subscribe((userDetail) => {
      if (!userDetail) return;

      this.userDetail = userDetail;
      this.createAccountFrom();
      this.getFindeksByCustomerId(userDetail.customerId);
    });
  }
Example #16
Source File: auth.interceptor.ts    From auth0-angular with MIT License 6 votes vote down vote up
/**
   * Tries to match a route from the SDK configuration to the HTTP request.
   * If a match is found, the route configuration is returned.
   * @param request The Http request
   * @param config HttpInterceptorConfig
   */
  private findMatchingRoute(
    request: HttpRequest<any>,
    config: HttpInterceptorConfig
  ): Observable<ApiRouteDefinition | null> {
    return from(config.allowedList).pipe(
      first((route) => this.canAttachToken(route, request), null)
    );
  }
Example #17
Source File: login.component.ts    From angular-10-basic-authentication-example with MIT License 6 votes vote down vote up
onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.loginForm.invalid) {
            return;
        }

        this.loading = true;
        this.authenticationService.login(this.f.username.value, this.f.password.value)
            .pipe(first())
            .subscribe(
                data => {
                    this.router.navigate([this.returnUrl]);
                },
                error => {
                    this.error = error;
                    this.loading = false;
                });
    }
Example #18
Source File: edit-account.component.ts    From angular-10-facebook-login-example with MIT License 6 votes vote down vote up
ngOnInit() {
        this.form = this.formBuilder.group({
            name: ['', Validators.required],
            extraInfo: ['']
        });

        // get account and populate form
        const id = this.route.snapshot.params['id'];
        this.accountService.getById(id)
            .pipe(first())
            .subscribe(x => {
                this.account = x;
                this.form.patchValue(x);
            });
    }
Example #19
Source File: login.component.ts    From angular-10-jwt-authentication-example with MIT License 6 votes vote down vote up
onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.loginForm.invalid) {
            return;
        }

        this.loading = true;
        this.authenticationService.login(this.f.username.value, this.f.password.value)
            .pipe(first())
            .subscribe({
                next: () => {
                    // get return url from route parameters or default to '/'
                    const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
                    this.router.navigate([returnUrl]);
                },
                error: error => {
                    this.error = error;
                    this.loading = false;
                }
            });
    }
Example #20
Source File: login.component.ts    From angular-10-jwt-refresh-tokens with MIT License 6 votes vote down vote up
onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.loginForm.invalid) {
            return;
        }

        this.loading = true;
        this.authenticationService.login(this.f.username.value, this.f.password.value)
            .pipe(first())
            .subscribe({
                next: () => {
                    this.router.navigate([this.returnUrl]);
                },
                error: error => {
                    this.error = error;
                    this.loading = false;
                }
            });
    }
Example #21
Source File: login.component.ts    From angular-10-registration-login-example with MIT License 6 votes vote down vote up
onSubmit() {
        this.submitted = true;

        // reset alerts on submit
        this.alertService.clear();

        // stop here if form is invalid
        if (this.form.invalid) {
            return;
        }

        this.loading = true;
        this.accountService.login(this.f.username.value, this.f.password.value)
            .pipe(first())
            .subscribe({
                next: () => {
                    // get return url from query parameters or default to home page
                    const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
                    this.router.navigateByUrl(returnUrl);
                },
                error: error => {
                    this.alertService.error(error);
                    this.loading = false;
                }
            });
    }
Example #22
Source File: login.component.ts    From angular-10-role-based-authorization-example with MIT License 6 votes vote down vote up
onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.loginForm.invalid) {
            return;
        }

        this.loading = true;
        this.authenticationService.login(this.f.username.value, this.f.password.value)
            .pipe(first())
            .subscribe({
                next: () => {
                    // get return url from query parameters or default to home page
                    const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
                    this.router.navigateByUrl(returnUrl);
                },
                error: error => {
                    this.error = error;
                    this.loading = false;
                }
            });
    }
Example #23
Source File: forgot-password.component.ts    From angular-10-signup-verification-boilerplate with MIT License 6 votes vote down vote up
onSubmit() {
        this.submitted = true;

        // reset alerts on submit
        this.alertService.clear();

        // stop here if form is invalid
        if (this.form.invalid) {
            return;
        }

        this.loading = true;
        this.alertService.clear();
        this.accountService.forgotPassword(this.f.email.value)
            .pipe(first())
            .pipe(finalize(() => this.loading = false))
            .subscribe({
                next: () => this.alertService.success('Please check your email for password reset instructions'),
                error: error => this.alertService.error(error)
            });
    }
Example #24
Source File: add-edit.component.ts    From angular-11-crud-example with MIT License 6 votes vote down vote up
ngOnInit() {
        this.id = this.route.snapshot.params['id'];
        this.isAddMode = !this.id;
        
        // password not required in edit mode
        const passwordValidators = [Validators.minLength(6)];
        if (this.isAddMode) {
            passwordValidators.push(Validators.required);
        }

        const formOptions: AbstractControlOptions = { validators: MustMatch('password', 'confirmPassword') };
        this.form = this.formBuilder.group({
            title: ['', Validators.required],
            firstName: ['', Validators.required],
            lastName: ['', Validators.required],
            email: ['', [Validators.required, Validators.email]],
            role: ['', Validators.required],
            password: ['', [Validators.minLength(6), this.isAddMode ? Validators.required : Validators.nullValidator]],
            confirmPassword: ['', this.isAddMode ? Validators.required : Validators.nullValidator]
        }, formOptions);

        if (!this.isAddMode) {
            this.userService.getById(this.id)
                .pipe(first())
                .subscribe(x => this.form.patchValue(x));
        }
    }
Example #25
Source File: login.component.ts    From angular-9-jwt-authentication-example with MIT License 6 votes vote down vote up
onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.loginForm.invalid) {
            return;
        }

        this.loading = true;
        this.authenticationService.login(this.f.username.value, this.f.password.value)
            .pipe(first())
            .subscribe(
                data => {
                    this.router.navigate([this.returnUrl]);
                },
                error => {
                    this.error = error;
                    this.loading = false;
                });
    }
Example #26
Source File: add-edit.component.ts    From angular-master-details-crud-example with MIT License 6 votes vote down vote up
ngOnInit() {
        this.id = this.route.snapshot.params['id'];
        this.isAddMode = !this.id;
        
        // password not required in edit mode
        const passwordValidators = [Validators.minLength(6)];
        if (this.isAddMode) {
            passwordValidators.push(Validators.required);
        }

        this.form = this.formBuilder.group({
            title: ['', Validators.required],
            firstName: ['', Validators.required],
            lastName: ['', Validators.required],
            email: ['', [Validators.required, Validators.email]],
            role: ['', Validators.required],
            password: ['', [Validators.minLength(6), this.isAddMode ? Validators.required : Validators.nullValidator]],
            confirmPassword: ['', this.isAddMode ? Validators.required : Validators.nullValidator]
        }, {
            validator: MustMatch('password', 'confirmPassword')
        });

        if (!this.isAddMode) {
            this.userService.getById(this.id)
                .pipe(first())
                .subscribe(x => this.form.patchValue(x));
        }
    }
Example #27
Source File: BleTransport.ts    From Elastos.Essentials.App with MIT License 6 votes vote down vote up
// TODO we probably will do this at end of open
  async inferMTU() {
    let { mtu } = this.device;
    await this.exchangeAtomicImpl(async () => {
      Logger.log(TAG, "inferMTU exchangeAtomicImpl");
      try {
        mtu =
          (await merge(
            this.notifyObservable.pipe(
              first((buffer) => buffer.readUInt8(0) === 0x08),
              map((buffer) => buffer.readUInt8(5))
            ),
            defer(() => from(this.write(Buffer.from([0x08, 0, 0, 0, 0])))).pipe(
              ignoreElements()
            )
          ).toPromise()) + 3;
      } catch (e: any) {
        Logger.log(TAG, "inferMTU got error:", String(e));
        await bleManager.disconnect(this.id).catch(() => {}); // but we ignore if disconnect worked.

        throw remapError(e);
      }
    });

    if (mtu > 23) {
      const mtuSize = mtu - 3;
      this.mtuSize = mtuSize;
    }

    return this.mtuSize;
  }
Example #28
Source File: auth.interceptor.ts    From dating-client with MIT License 6 votes vote down vote up
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.store.select(selectAuthToken).pipe(
      first(),
      switchMap(token => {
        const authRequest = !!token
          ? req.clone({ setHeaders: { Authorization: `Bearer ${ token }` } })
          : req;
        return next.handle(authRequest);
      })
    );
  }
Example #29
Source File: router-search.service.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
updateSearch(params: SearchFilters): void {
    this.searchFacade.searchFilters$
      .pipe(
        first(),
        map((filters) => ({ ...filters, ...params })),
        map((filters) => stateToRouteParams(filters))
      )
      .subscribe((filters) => this.facade.updateSearch(filters))
  }