@angular/core#OnDestroy TypeScript Examples

The following examples show how to use @angular/core#OnDestroy. 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: sites-connected.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
@Component({
  selector: 'app-sites-connected',
  templateUrl: './sites-connected.component.html',
  styleUrls: ['./sites-connected.component.scss']
})
export class SitesConnectedComponent implements OnInit, OnDestroy {
  componentDestroyed$: Subject<void> = new Subject<void>();
  sitesConnected$: Observable<ISiteConnection[]> = this.sitesConnectionsQuery.selectAll();

  constructor(
    private readonly sitesConnectionsQuery: SitesConnectionsQuery,
    private nzDrawerService: NzDrawerService,
    private readonly translateService: TranslateService,
  ) { }

  ngOnInit(): void {
  }

  ngOnDestroy(): void {
    this.componentDestroyed$.next();
    this.componentDestroyed$.complete();
  }

  async onSiteConnected(siteConnected: ISiteConnection): Promise<void> {
    const drawerRef = await this.nzDrawerService.create<ConnectedSiteDetailsComponent>({
      nzContent: ConnectedSiteDetailsComponent,
      nzContentParams: {
        connectedSite: siteConnected
      },
      nzTitle: this.translateService.instant('SETTINGS.SITES_CONNECTED.SELECT_SITE_TITLE'),
      nzWrapClassName: 'drawer-full-w-320',
    });

    drawerRef.open();
  }

}
Example #2
Source File: flex.directive.ts    From ng-devui-admin with MIT License 6 votes vote down vote up
@Directive({
  selector: `[daFlex], [daFlexMs], [daFlexMm], [daFlexMl], [daFlexXs], [daFlexSm], [daFlexMd], [daFlexLg], [daFlexXl]`,
})

export class DaFlexDirective implements OnInit, OnDestroy {
  private destroy$ = new Subject();

  @Input() daFlex: number | string;
  @Input() daFlexMs: number | string;
  @Input() daFlexMn: number | string;
  @Input() daFlexMl: number | string;
  @Input() daFlexXs: number | string;
  @Input() daFlexSm: number | string;
  @Input() daFlexMd: number | string;
  @Input() daFlexLg: number | string;
  @Input() daFlexXl: number | string;

  constructor(
    private elementRef: ElementRef,
    private renderer: Renderer2,
    private screenQueryService: DaScreenMediaQueryService
  ) { }

  ngOnInit(): void {
    this.screenQueryService.getPoint()
    .pipe(takeUntil(this.destroy$))
    .subscribe(( {currentPoint }) => {
      setScreenPointFlex(currentPoint, this, this.elementRef, this.renderer);
    });
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
Example #3
Source File: fire-admin.component.ts    From FireAdmin with MIT License 6 votes vote down vote up
@Component({
  selector: 'fa-root',
  template: `<router-outlet (deactivate)="clearAlert()"></router-outlet>`,
  styleUrls: ['./fire-admin.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class FireAdminComponent implements OnInit, OnDestroy {

  constructor(private alert: AlertService, private currentUser: CurrentUserService) { }

  ngOnInit() {
  }

  ngOnDestroy() {
    this.currentUser.unsubscribe();
  }

  clearAlert() {
    if (! this.alert.isPersistent) {
      this.alert.clear();
    }
  }

}
Example #4
Source File: notification.component.ts    From ng-conf-2020-workshop with MIT License 6 votes vote down vote up
@Component({
  selector: 'app-notification',
  templateUrl: './notification.component.html',
  styleUrls: ['./notification.component.scss']
})
export class NotificationComponent implements OnDestroy {

  private destroy$ = new Subject();

  @ViewChild('toast', { static: true })
  private toast: IgxToastComponent;

  constructor(private eventBus: EventBusService) {
    this.eventBus.success.pipe(takeUntil(this.destroy$)).subscribe(m => this.showMessage(m.text));
    this.eventBus.error.pipe(takeUntil(this.destroy$)).subscribe(m => this.showMessage(m.text, true));
    this.eventBus.message.pipe(takeUntil(this.destroy$)).subscribe(m => this.showMessage(m.text));
  }

  public errorState = false;

  public showMessage(message: string, error = false) {
    this.errorState = error;
    this.toast.show(message);
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
Example #5
Source File: ngx-colors.component.ts    From ngx-colors with MIT License 6 votes vote down vote up
@Component({
  selector: 'ngx-colors',
  templateUrl: './ngx-colors.component.html',
  styleUrls: ['./ngx-colors.component.scss'],
})
export class NgxColorsComponent implements OnInit, OnDestroy {
  private triggerDirectiveColorChangeSubscription: Subscription | null = null;

  constructor(
    private cdRef: ChangeDetectorRef,
    @Host() private triggerDirective: NgxColorsTriggerDirective
  ) {}

  ngOnInit(): void {
    this.triggerDirectiveColorChangeSubscription =
      this.triggerDirective.change.subscribe((color) => {
        this.color = color;
        this.cdRef.markForCheck();
      });
  }

  ngOnDestroy(): void {
    if (this.triggerDirectiveColorChangeSubscription) {
      this.triggerDirectiveColorChangeSubscription.unsubscribe();
    }
  }

  //IO color
  color: string = this.triggerDirective.color;
}
Example #6
Source File: modal-trigger.directive.ts    From canopy with Apache License 2.0 6 votes vote down vote up
@Directive({
  selector: '[lgModalTrigger]',
})
export class LgModalTriggerDirective implements OnInit, OnDestroy {
  private allowFocusOnModalTrigger: boolean;
  private subscription: Subscription;

  @Input() lgModalTrigger: string;
  @Output() clicked: EventEmitter<void> = new EventEmitter();

  constructor(private el: ElementRef, private modalService: LgModalService) {}

  @HostListener('click') openModal(): void {
    this.allowFocusOnModalTrigger = true;
    this.modalService.open(this.lgModalTrigger);
    this.clicked.emit();
  }

  ngOnInit(): void {
    this.subscription = this.modalService
      .isOpen$(this.lgModalTrigger)
      .pipe(
        filter(isOpen => !isOpen && this.allowFocusOnModalTrigger),
        map(() => {
          (this.el.nativeElement as HTMLElement).focus();
        }),
      )
      .subscribe();
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}
Example #7
Source File: childTest.c.ts    From ngx-dynamic-hooks with MIT License 6 votes vote down vote up
@Component({
  selector: 'dynhooks-childtest',
  templateUrl: './childTest.c.html',
  styleUrls: ['./childTest.c.scss'],
})
export class ChildTestComponent implements DoCheck, OnInit, OnChanges, AfterViewInit, OnDestroy {

  constructor(private cd: ChangeDetectorRef, @Optional() @Inject(BLUBBSERVICETOKEN) private blubbService: any) {
    console.log('CHILD_TEST', this.blubbService);
  }


  ngOnInit () {
    // console.log('textbox init');
  }

  ngOnChanges(changes: any) {
    // console.log('textbox changes');
  }

  ngDoCheck() {
    // console.log('textbox doCheck');
  }

  ngAfterViewInit() {
    // console.log('textbox afterviewinit');
  }

  ngOnDestroy() {
    // console.log('textbox destroy');
  }

}
Example #8
Source File: theme.service.ts    From nica-os with MIT License 6 votes vote down vote up
@Injectable()
export class ThemeService implements OnDestroy {
  appSettings$ = this.store$.pipe(select(selectAppSettings));
  private subs: Subscription[] = [];

  constructor(private store$: Store<AppState>) {
    this.subs.push(
      this.appSettings$.pipe(
        first(),
        map(({theme}) => {
          this.setTheme(theme);
        })
      ).subscribe()
    );
  }

  ngOnDestroy() {
    this.subs.map(s => s.unsubscribe());
  }

  setTheme(name: string) {
    const themeName = `${name}-theme`;
    const classList = document.body.classList;
    classList.forEach(className => { if (className === themeName) { return; } else { classList.remove(className); } });
    classList.add(themeName);
    (document.body.parentElement as any).classList = classList;
    window.localStorage.setItem('nos_th', name);
  }
}
Example #9
Source File: randomrecipe.component.ts    From TheHungryRecipesApp with GNU General Public License v3.0 6 votes vote down vote up
@Component({
  selector: 'app-randomrecipe',
  templateUrl: './randomrecipe.component.html',
  styleUrls: ['./randomrecipe.component.scss']
})
export class RandomrecipeComponent implements OnInit, OnDestroy {
  meal: Meal;

  ngUnsubscribe: Subject<void> = new Subject();

  constructor(
    private appService: AppService
  ) { }

  ngOnInit(): void {
    this.fetchRandomRecipe();
  }

  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

  fetchRandomRecipe(): void {
    this.appService.getRandomMeal()
      .pipe(takeUntil(this.ngUnsubscribe))
      .subscribe((meal: Meal) => this.meal = meal);
  }

}
Example #10
Source File: main-layout.component.ts    From leapp with Mozilla Public License 2.0 6 votes vote down vote up
@Component({
  selector: "app-main-layout",
  templateUrl: "./main-layout.component.html",
  styleUrls: ["./main-layout.component.scss"],
})
export class MainLayoutComponent implements OnInit, OnDestroy {
  compactMode: boolean;

  private subscription;

  constructor(private electronService: AppNativeService) {
    this.subscription = compactMode.subscribe((value) => {
      this.compactMode = value;
      this.electronService.ipcRenderer.send("resize-window", { compactMode: this.compactMode });
    });
  }

  ngOnInit(): void {}

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

  clearOptionBarIds(): void {
    for (const prop of Object.getOwnPropertyNames(optionBarIds)) {
      optionBarIds[prop] = false;
    }
    document.querySelector(".sessions").classList.remove("option-bar-opened");
  }
}
Example #11
Source File: dashboard.component.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss'],
})
export class DashboardComponent implements OnInit, OnDestroy {
  constructor(private route: ActivatedRoute, private router: Router) {}
  lodash = _;
  projectDataTableType = 'user';

  ngOnDestroy(): void {}

  async ngOnInit() {
    if (this.route.snapshot.paramMap.get('projectDataTableType')) {
      this.projectDataTableType = this.route.snapshot.paramMap.get('projectDataTableType');
    }
    this.router.routeReuseStrategy.shouldReuseRoute = () => false;
    this.router.events.subscribe((evt) => {
      if (evt instanceof NavigationEnd) {
        this.router.navigated = false;
      }
    });
  }
}
Example #12
Source File: home.component.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit, OnDestroy {
  subscription: Subscription = null;
  inputStreamData = ['john wick', 'inception', 'interstellar'];
  outputStreamData = [];

  constructor() {}

  ngOnInit() {}

  ngOnDestroy() {
    this.stopStream();
  }

  startStream() {
    const streamSource = interval(1500);
    this.subscription = streamSource.subscribe((input) => {
      this.outputStreamData.push(input);
      console.log('stream output', input);
    });
  }

  stopStream() {
    this.subscription.unsubscribe();
    this.subscription = null;
  }
}
Example #13
Source File: tutorial-dialog.component.ts    From bdc-walkthrough with MIT License 5 votes vote down vote up
@Component({
  selector: 'bdc-walk-dialog',
  templateUrl: './tutorial-dialog.component.html',
  styleUrls: ['./tutorial-dialog.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class BdcWalkDialogComponent implements AfterContentInit, OnDestroy, OnChanges {
  @Input() name: string;
  @Input() mustCompleted: { [taskName: string]: any | boolean } = {};
  @Input() mustNotDisplaying: string[] = [];
  @Input() width = '500px';
  @Output() opened = new EventEmitter<void>();
  @Output() closed = new EventEmitter<void>();
  @ViewChild(TemplateRef, {static: true}) templateRef: TemplateRef<any>;

  dialogRef: MatDialogRef<any>;
  componentSubscription: Subscription;

  constructor(private dialog: MatDialog,
              private tutorialService: BdcWalkService) { }

  ngAfterContentInit() {
    this.componentSubscription = this.tutorialService.changes.subscribe(() => this._sync());
  }

  ngOnChanges(): void {
    this._sync();
  }

  ngOnDestroy() {
    if (this.componentSubscription) {
      this.componentSubscription.unsubscribe();
    }

    this._close();
  }

  getValue(taskName: string): any {
    return this.tutorialService.getTaskCompleted(taskName);
  }

  close(setTasks: { [taskName: string]: any | boolean } = {}) {
    this.tutorialService.logUserAction(this.name, BdcDisplayEventAction.UserClosed);
    this.tutorialService.setTaskCompleted(this.name);
    this.tutorialService.setTasks(setTasks);
  }

  private _open() {
    this.dialogRef = this.dialog.open(this.templateRef, {width: this.width, disableClose: true, restoreFocus: false, panelClass: 'bdc-walk-dialog'});
    this.opened.emit();
  }

  private _close() {
    if (this.dialogRef) {
      this.dialogRef.close();
      this.dialogRef = null;
      this.closed.emit();
    }
  }

  private _sync() {
    if (this.name) {
      if (!this.tutorialService.getTaskCompleted(this.name) &&
        !this.tutorialService.disabled &&
        this.tutorialService.evalMustCompleted(this.mustCompleted) &&
        this.tutorialService.evalMustNotDisplaying(this.mustNotDisplaying)) {

        if (!this.dialogRef) {
          this._open();
          this.tutorialService.setIsDisplaying(this.name, true);
        }
      } else if (this.dialogRef) {
        this._close();
        this.tutorialService.setIsDisplaying(this.name, false);
      }
    }
  }
}
Example #14
Source File: edit-wallet-name.component.ts    From xBull-Wallet with GNU Affero General Public License v3.0 5 votes vote down vote up
@Component({
  selector: 'app-edit-wallet-name',
  templateUrl: './edit-wallet-name.component.html',
  styleUrls: ['./edit-wallet-name.component.scss']
})
export class EditWalletNameComponent implements OnInit, OnDestroy {
  componentDestroyed$: Subject<void> = new Subject<void>();

  wallet$: ReplaySubject<IWallet> = new ReplaySubject<IWallet>();
  @Input() set wallet(data: IWallet) {
    this.wallet$.next(data);
  }

  nameField: FormControl = new FormControl('', Validators.required);

  constructor(
    private readonly walletsService: WalletsService,
    private readonly nzMessageService: NzMessageService,
    private readonly nzDrawerRef: NzDrawerRef,
    private readonly translateService: TranslateService,
  ) { }

  ngOnInit(): void {
  }

  ngOnDestroy(): void {
    this.componentDestroyed$.next();
    this.componentDestroyed$.complete();
  }

  async onConfirm(): Promise<void> {
    const wallet = await this.wallet$.pipe(take(1)).toPromise();
    if (!wallet) {
      // TODO: Add error here later
      return;
    }

    this.walletsService.updateWalletName(wallet._id, this.nameField.value);

    this.nzMessageService.success(`${this.translateService.instant('SUCCESS_MESSAGE.VALUE_UPDATED')}: "${this.nameField.value}"`);

    this.nzDrawerRef.close();
  }

}
Example #15
Source File: rubic-button.component.ts    From rubic-app with GNU General Public License v3.0 5 votes vote down vote up
@Component({
  selector: 'app-rubic-button',
  templateUrl: './rubic-button.component.html',
  styleUrls: ['./rubic-button.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RubicButtonComponent implements OnInit, OnDestroy {
  @HostBinding('class') @Input('class') classList: string;

  @Input() appearance: TuiAppearance | string = 'primary';

  @Input() size: TuiSizeXS | TuiSizeXL = 'l';

  @Input() pseudoHovered: boolean | null = null;

  @Input('bordered') set setBorder(border: boolean | '') {
    this._border = border === '' || border;
  }

  @Input('fullWidth') set fullWidth(fullWidth: boolean | '') {
    this._fullWidth = fullWidth === '' || fullWidth;
  }

  @Input('disabled') set disabled(disabled: boolean | '') {
    this._disabled = disabled === '' || disabled;
  }

  @Input() loading = false;

  @Output() onClick = new EventEmitter<Event>();

  public _border: boolean;

  public _fullWidth: boolean;

  public _disabled = false;

  public themeSubscription$: Subscription;

  constructor(private readonly themeService: ThemeService) {
    this._fullWidth = true;
  }

  public ngOnInit(): void {
    this.themeSubscription$ = this.themeService.theme$.subscribe(el => {
      if (!this.classList) {
        this.classList = '';
      }
      this.classList =
        el === 'dark' ? `${this.classList} dark` : this.classList.replace(' dark', '');
    });
  }

  public ngOnDestroy(): void {
    this.themeSubscription$.unsubscribe();
  }

  public buttonClick(event: Event): void {
    if (!this._disabled) {
      this.onClick.emit(event);
    }
  }
}
Example #16
Source File: screen-media-query.service.ts    From ng-devui-admin with MIT License 5 votes vote down vote up
@Injectable({ providedIn: 'root' })
export class DaScreenMediaQueryService implements OnDestroy {
  private currentPoint: DaBreakpoint;
  private pointChangeSub: ReplaySubject<{ currentPoint: DaBreakpoint; change: number; compare: { [key: string]: number } }> =
    new ReplaySubject(1);
  private destroy$ = new Subject();

  // 可以传入一个基准point,返回数据结构{ currentPoint, 变大or变小or没变,比基准point大or小or一样 }
  public getPoint(): ReplaySubject<{ currentPoint: DaBreakpoint; change: number; compare: { [key: string]: number } }> {
    if (!this.currentPoint) {
      this.currentPoint = this.getCurrentPoint()!;
      this.pointChangeSub.next({
        currentPoint: this.currentPoint,
        change: 0,
        compare: this.comparePoints(this.currentPoint),
      });

      fromEvent(window, 'resize')
        .pipe(takeUntil(this.destroy$))
        .subscribe(() => {
          const tempPoint = this.getCurrentPoint()!;
          if (this.currentPoint !== tempPoint) {
            const change = this.comparePoints(tempPoint, this.currentPoint) as number;
            this.currentPoint = tempPoint;

            this.pointChangeSub.next({
              currentPoint: this.currentPoint,
              change: change,
              compare: this.comparePoints(tempPoint),
            });
          }
        });
    }

    return this.pointChangeSub;
  }

  // 无p2,则全量对比
  private comparePoints(p1: DaBreakpoint, p2?: DaBreakpoint) {
    let index1: any, index2: any;
    for (let i = 0; i < DaBreakpoints.length; i++) {
      if (p1 === DaBreakpoints[i]) {
        index1 = i;
      }
      if (p2 === DaBreakpoints[i]) {
        index2 = i;
      }
    }

    if (!p2) {
      let res: any = {};
      DaBreakpoints.forEach((point, index) => {
        res[point] = index1 - index;
      });

      return res;
    }

    return index1 - index2;
  }

  private getCurrentPoint(): DaBreakpoint | undefined {
    const currentScreenWidth = window.innerWidth;
    for (let i = 0; i < DaBreakpoints.length; i++) {
      if (DaBreakpointsMap[DaBreakpoints[i]] >= currentScreenWidth || i === DaBreakpoints.length - 1) {
        return DaBreakpoints[i] as DaBreakpoint;
      }
    }
    return;
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
Example #17
Source File: login.component.ts    From FireAdmin with MIT License 5 votes vote down vote up
@Component({
  selector: 'fa-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit, OnDestroy {

  logo: string = getLogo();
  email: string = '';
  password: string = '';
  rememberMe: boolean = false;
  error: string = null;
  private routeSubscription: Subscription = null;

  constructor(private auth: AuthService, private route: ActivatedRoute, private navigation: NavigationService) { }

  ngOnInit() {
    this.routeSubscription = this.route.queryParams.subscribe((params: any) => {
      //console.log(params);
      if (params.email) {
        this.email = params.email;
      }
      if (params.password) {
        this.password = params.password;
      }
    });
  }

  ngOnDestroy() {
    if (this.routeSubscription) {
      this.routeSubscription.unsubscribe();
    }
  }

  onSubmit() {
    this.auth.signIn(this.email, this.password, this.rememberMe).then(() => {
      this.navigation.redirectTo('dashboard');
    }).catch((error: Error) => {
      this.error = error.message;
    });
  }

  dismissError(event: Event) {
    event.preventDefault();
    event.stopPropagation();
    this.error = null;
  }

}
Example #18
Source File: feature-toggle.directive.ts    From canopy with Apache License 2.0 5 votes vote down vote up
@Directive({
  selector: '[lgFeatureToggle]',
})
export class LgFeatureToggleDirective implements OnInit, OnDestroy {
  subscription: Subscription;

  @Input() lgFeatureToggle: string;

  constructor(
    private lgFeatureToggleService: LgFeatureToggleService,
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    @Optional()
    @Inject(togglesOptionsInjectable)
    private options?: LgFeatureToggleOptions,
  ) {}

  ngOnInit(): void {
    this.subscription = this.lgFeatureToggleService.toggles$
      .pipe(
        tap(() => this.viewContainer.clear()),
        filter(
          (toggles: LgFeatureToggleConfig) =>
            (toggles[this.lgFeatureToggle] === undefined && !this.isDefaultHideSet()) ||
            toggles[this.lgFeatureToggle],
        ),
      )
      .subscribe(() => {
        this.viewContainer.createEmbeddedView(this.templateRef);
      });
  }

  public setOptions(options: LgFeatureToggleOptions): void {
    this.options = options;
  }

  ngOnDestroy(): void {
    this.subscription?.unsubscribe();
  }

  private isDefaultHideSet(): boolean {
    return this.options && this.options.defaultHide;
  }
}
Example #19
Source File: inlineTest.c.ts    From ngx-dynamic-hooks with MIT License 5 votes vote down vote up
@Component({
  selector: 'dynhooks-inlinetest',
  templateUrl: './inlineTest.c.html',
  styleUrls: ['./inlineTest.c.scss'],
})
export class InlineTestComponent implements OnDynamicMount, OnDynamicChanges, DoCheck, OnInit, OnChanges, AfterViewInit, OnDestroy {
  @Input() backgroundColor: string = '#25436c';
  @Input() nr!: number;
  @Input() config: any;
  mountContext: any;
  mountContentChildren!: Array<DynamicContentChild>;
  changesContext: any;
  changesContentChildren!: Array<DynamicContentChild>;

  constructor(private cd: ChangeDetectorRef) {
  }

  ngOnInit () {
    // console.log('textbox init');
  }

  ngOnChanges(changes: any) {
    // console.log('textbox changes');
  }

  ngDoCheck() {
    // console.log('textbox doCheck');
  }

  ngAfterViewInit() {
    // console.log('textbox afterviewinit');
  }

  ngOnDestroy() {
    // console.log('textbox destroy');
  }

  onDynamicMount(data: OnDynamicData) {
    this.mountContext = data.context;
    this.mountContentChildren = (data as any).contentChildren;
  }

  onDynamicChanges(data: OnDynamicData) {
    if (data.hasOwnProperty('context')) {
      this.changesContext = data.context;
    }
    if (data.hasOwnProperty('contentChildren')) {
      this.changesContentChildren = (data as any).contentChildren;
    }
  }

}
Example #20
Source File: web3-modal.component.ts    From web3modal-angular with MIT License 5 votes vote down vote up
@Component({
  selector: 'm-web3-modal',
  templateUrl: 'web3-modal.component.html',
  styleUrls: ['./web3-modal.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class Web3ModalComponent implements OnInit, OnDestroy {
  open = false;
  providers: IProviderUserOptions[] = [];
  showMetamaskDownload: boolean;

  private openSubscription: Subscription;
  private providersSubscription: Subscription;
  private readonly metamaskShopURL = 'https://metamask.io/download.html';

  @Input() title: string;
  @Input() description?: string;
  @Input() descriptionGray?: string;
  @Input() dismissText?: string;
  @Input() promptMetamaskIfNotInstalled = false;

  constructor(private service: Web3ModalService) {}

  ngOnInit(): void {
    this.openSubscription = this.service.shouldOpen.subscribe({
      next: (open: boolean) => {
        this.open = open;
      },
    });

    this.providersSubscription = this.service.providers.subscribe({
      next: (providers: IProviderUserOptions[]) => {
        this.showMetamaskDownload =
          this.promptMetamaskIfNotInstalled &&
          !this.isMetamaskInProviders(providers);
        this.providers = providers;
      },
    });
  }

  ngOnDestroy(): void {
    this.openSubscription.unsubscribe();
    this.providersSubscription.unsubscribe();
  }

  close(): void {
    this.service.close();
  }

  private isMetamaskInProviders(providers: IProviderUserOptions[]): boolean {
    return providers.some((p) => p.name.toLowerCase() === 'metamask');
  }

  private openMetamaskDownloadPage(): void {
    window.open(this.metamaskShopURL, '_blank');
  }
}
Example #21
Source File: daily-photos.component.ts    From mylog14 with GNU General Public License v3.0 5 votes vote down vote up
@Component({
  selector: 'app-daily-photos',
  templateUrl: './daily-photos.component.html',
  styleUrls: ['./daily-photos.component.scss'],
})
export class DailyPhotosComponent implements OnInit, OnDestroy {
  destroy$ = new Subject();

  @Input() date: string;
  records$ = this.dataStore.recordsByDate$
    .pipe(
      map(recordsByDate => recordsByDate[this.date]),
      map(records => {
        if (records) {
          return records.filter(record =>
            record.fields.find(field => field.type === RecordFieldType.photo && field.value)
          );
        } else {
          return records;
        }
      })
    );

  constructor(
    private readonly dataStore: DataStoreService,
    private readonly modalService: ModalService,
    private readonly router: Router,
  ) { }

  ngOnInit() {
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  showPhotoViewer(record: Record) {
    this.modalService.showPhotoViewerModal(record)
      .pipe(
        switchMap(() => this.records$),
        switchMap(records => (records) ? of() : this.router.navigate(['/'])),
        takeUntil(this.destroy$),
      ).subscribe();
  }

}
Example #22
Source File: export-package.component.ts    From msfs-community-downloader with GNU Affero General Public License v3.0 5 votes vote down vote up
@Component({
    selector: 'app-export-package',
    templateUrl: './export-package.component.html',
    styleUrls: ['../../core/common.scss', './export-package.component.scss']
})
export class ExportPackageComponent implements OnInit, OnDestroy {
    faTimes = faTimes;

    sub: Subscription;

    exportablePackage: ExportablePackage;
    json: string;

    constructor(
        private settingsService: SettingsService,
        private electronService: ElectronService,
        private activatedRoute: ActivatedRoute,
        private domainService: DomainService
    ) { }

    ngOnInit(): void {
        this.sub = this.activatedRoute.params.subscribe(params => {
            const id = params['id'];
            if (id) {
                const p = this.domainService.getPackages().find(x => x.id === id);
                this.exportablePackage = new ExportablePackage();

                this.exportablePackage.id = p.id;
                this.exportablePackage.name = p.name;
                this.exportablePackage.description = p.description;
                this.exportablePackage.githubOwner = p.githubOwner;
                this.exportablePackage.githubRepo = p.githubRepo;
                this.exportablePackage.assetName = p.assetName;
                this.exportablePackage.isPrerelease = p.isPrerelease;
                this.exportablePackage.versionPatternToRemove = p.versionPatternToRemove;
                this.exportablePackage.folderName = p.folderName;
                this.exportablePackage.illustration = p.illustration;
                this.exportablePackage.summary = p.summary;
                this.exportablePackage.webpageUrl = p.webpageUrl;
                this.exportablePackage.oldFolderNames = p.oldFolderNames;
                this.exportablePackage.minSoftwareVersion = p.minSoftwareVersion;
                this.exportablePackage.releaseType = p.releaseType;
                this.exportablePackage.branchName = p.branchName;
                this.exportablePackage.releaseBranchTag = p.releaseBranchTag;

                if(!this.exportablePackage.minSoftwareVersion) this.exportablePackage.minSoftwareVersion = this.settingsService.getVersion();

                this.json = JSON.stringify(this.exportablePackage);
            }
        });
    }

    ngOnDestroy(): void {
        if (this.sub) this.sub.unsubscribe();
    }

    saveFile(): boolean {
        const res = this.electronService.remote.dialog.showSaveDialogSync(
            {
                title: 'Select the export file',
                defaultPath: `${this.exportablePackage.folderName}.json`,
                filters: [{ name: 'Json', extensions: ['json'] }],

            });

        if (res) {
            this.electronService.fs.writeFileSync(res, this.json, 'utf-8');
        }
        return false;
    }
}
Example #23
Source File: category.component.ts    From TheHungryRecipesApp with GNU General Public License v3.0 5 votes vote down vote up
@Component({
  selector: 'app-category',
  templateUrl: './category.component.html',
  styleUrls: ['./category.component.scss']
})

export class CategoryComponent implements OnInit, OnDestroy {

  categoryName: string;
  recipesBySpecificCategory = [];
  categoryInfo: any;

  ngUnsubscribe: Subject<void> = new Subject();

  constructor(
    private route: ActivatedRoute,
    private appService: AppService
  ) { }

  ngOnInit(): void {
    this.getCategory();

    this.getRecipesByCategory(this.categoryName);

    this.categoryInfo = this.appService.getCategoryData(this.categoryName);
  }

  ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

  // Get ':category' param value
  getCategory(): void {
    this.categoryName = this.route.snapshot.paramMap.get('category');
  }

  // Get category info
  getRecipesByCategory(categoryName: string): void {
    this.appService.getRecipesByCategory(categoryName)
      .pipe(takeUntil(this.ngUnsubscribe))
      .subscribe(data => {
        data.meals.forEach((meal, index) => {
          this.recipesBySpecificCategory[index] = meal;
        });
        this.appService.setRecipesByCategory(this.recipesBySpecificCategory);
      });
  }
}
Example #24
Source File: column-dialog.component.ts    From leapp with Mozilla Public License 2.0 5 votes vote down vote up
@Component({
  selector: "app-column-dialog",
  templateUrl: "./column-dialog.component.html",
  styleUrls: ["./column-dialog.component.scss"],
})
export class ColumnDialogComponent implements OnInit, OnDestroy {
  eGlobalColumns: IGlobalColumns;

  columnForm = new FormGroup({
    role: new FormControl(),
    provider: new FormControl(),
    namedProfile: new FormControl(),
    region: new FormControl(),
  });

  showRegion;

  private subscription;
  private subscription2;
  private values;

  constructor(private bsModalRef: BsModalRef, private appService: AppService) {}

  ngOnInit(): void {
    // Set new state
    this.subscription = this.columnForm.valueChanges.subscribe((values: IGlobalColumns) => {
      this.values = values;
    });

    this.subscription2 = compactMode.subscribe((value) => (this.showRegion = !value));

    Object.keys(this.eGlobalColumns).forEach((key) => {
      this.columnForm.get(key).setValue(this.eGlobalColumns[key]);
    });
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
    this.subscription2.unsubscribe();
  }

  closeModal(): void {
    this.appService.closeModal();
  }

  setColumns(): void {
    globalColumns.next(this.values);
    this.appService.closeModal();
  }
}
Example #25
Source File: bill-of-materials.component.ts    From barista with Apache License 2.0 5 votes vote down vote up
@Component({
  selector: 'app-bill-of-materials',
  templateUrl: './bill-of-materials.component.html',
  styleUrls: ['./bill-of-materials.component.scss'],
})
export class BillOfMaterialsComponent implements OnInit, AfterViewInit, OnDestroy {
  constructor(private bomGlobalFilterMessageService: BomGlobalFilterMessageService) {}

  filter = '';

  hasNoScans: boolean;

  @Input() project: Project;

  @ViewChild('searchInput') searchInput: ElementRef;

  clearSearchField() {
    this.filter = '';
    this.bomGlobalFilterMessageService.send('');
  }

  ngAfterViewInit(): void {
    if (!this.searchInput) {
      return;
    }

    fromEvent(this.searchInput.nativeElement, 'input')
      .pipe(
        map((event: any) => event.target.value),
        filter(res => res.length > 2 || res.length === 0),
        debounceTime(500),
        distinctUntilChanged(),
        untilDestroyed(this),
      )
      .subscribe((text: string) => {
        this.bomGlobalFilterMessageService.send(text);
      });
  }

  ngOnDestroy(): void {}

  ngOnInit() {
    if (this.project && this.project.wasImported) {
      this.hasNoScans = false;
    } else {
      this.hasNoScans = !this.project || _.isEmpty(this.project.scans);
    }
  }
}
Example #26
Source File: home.component.ts    From Angular-Cookbook with MIT License 5 votes vote down vote up
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit, OnDestroy {
  isComponentAlive: boolean;
  inputStreamData = ['john wick', 'inception', 'interstellar'];
  streamsOutput$: Observable<number[]>;
  outputStreamData = [];

  constructor() {}

  ngOnInit() {
    this.isComponentAlive = true;
    this.startStream();
  }

  ngOnDestroy() {
    this.stopStream();
  }

  startStream() {
    const streamSource = interval(1500);
    const secondStreamSource = interval(3000);
    const fastestStreamSource = interval(500);
    this.streamsOutput$ = merge(
      streamSource,
      secondStreamSource,
      fastestStreamSource
    ).pipe(
      takeWhile(() => !!this.isComponentAlive),
      map((output) => {
        console.log(output);
        this.outputStreamData = [...this.outputStreamData, output];
        return this.outputStreamData;
      })
    );
  }

  stopStream() {
    this.isComponentAlive = false;
  }
}
Example #27
Source File: manage.component.ts    From 1hop with MIT License 4 votes vote down vote up
@Component({
    selector: 'app-manage',
    templateUrl: './manage.component.html',
    styleUrls: ['./manage.component.scss'],
    encapsulation: ViewEncapsulation.None
})
export class ManageComponent implements OnInit, OnDestroy {

    compound = {
        lending: [],
        borrowing: []
    };

    maker = {
        dsr: 0,
        lending: [],
        borrowing: []
    };

    destroyed = false;
    sync = true;
    timer;

    constructor(
        private web3Service: Web3Service,
        private compoundService: CompoundService,
        private tokenService: TokenService,
        private makerService: MakerService
    ) {
    }

    async ngOnInit() {


        await this.loadPositions();

        setTimeout(() => {

            this.web3Service.connectEvent.subscribe(async () => {

                this.loadPositions();
            });

            this.web3Service.disconnectEvent.subscribe(async () => {

            });
        }, 1000);
    }

    @OnPageVisible()
    logWhenPageVisible(): void {

        // console.log('OnPageVisible => visible');
        this.sync = true;
    }

    @OnPageHidden()
    logWhenPageHidden(): void {

        // console.log('OnPageHidden => hidden');
        this.sync = false;
    }

    async runBackgroundJobs() {

        const startTime = (new Date()).getTime();

        try {

            if (this.sync) {

                const promises = [];

                if (
                    this.web3Service.walletAddress
                ) {

                    promises.push(
                        this.loadPositions()
                    );
                }

                await Promise.all(promises);
            }
        } catch (e) {

            console.error(e);
        }

        try {

            if (
                (new Date()).getTime() - startTime > 5000
            ) {

                this.runBackgroundJobs();
            } else {

                this.timer = setTimeout(() => {

                    if (!this.destroyed) {

                        this.runBackgroundJobs();
                    }
                }, 5000 - ((new Date()).getTime() - startTime));
            }
        } catch (e) {

            console.error(e);
        }
    }

    async loadPositions() {

        this.makerService.getDSR().then(value => this.maker.dsr = value);

        if (this.web3Service.walletAddress) {

            this.compound.lending = await Promise.all(
                (await this.compoundService.getBalances(this.web3Service.walletAddress))
                    .filter(position => position.balance != 0)
                    .map(async position => {

                        position['apy'] = this.tokenService.toFixed(
                            (await this.compoundService.interest(
                                position.address
                            )).annualLendRate,
                            2
                        );

                        return position;
                    })
            );

            this.compound.borrowing = await Promise.all(
                (await this.compoundService.getBorrowedBalances(this.web3Service.walletAddress))
                    .filter(position => position.rawBalance.gt(0))
                    .map(async position => {

                        position['apy'] = this.tokenService.toFixed(
                            (await this.compoundService.interest(
                                position.address
                            )).annualBorrowRate,
                            2
                        );

                        return position;
                    })
            );

            console.log('this.compound', this.compound);
        }
    }

    ngOnDestroy(): void {

        this.destroyed = true;
        clearTimeout(this.timer);
    }

}
Example #28
Source File: app.component.ts    From gnosis.1inch.exchange with MIT License 4 votes vote down vote up
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnDestroy {

    public openLoader = true;
    private updateAmounts = new Subject<QuoteUpdate>();
    private subscription = new Subscription();

    @LocalStorage('slippage', '3') slippage;
    @LocalStorage('fromAmount', '1') fromAmount: string;
    @LocalStorage('fromTokenSymbol', 'ETH') _fromTokenSymbol: string;
    @LocalStorage('toTokenSymbol', 'DAI') _toTokenSymbol: string;

    @LocalStorage('panelOpenState', false)
    panelOpenState: boolean;

    // @LocalStorage('gasPricePanelOpenState', false)
    // gasPricePanelOpenState: boolean;

    set fromTokenSymbol(symbol: string) {
        if (symbol === this.toTokenSymbol) {
            this.flipTokens();
            return;
        }
        this._fromTokenSymbol = symbol;
    }

    get fromTokenSymbol(): string {
        return this._fromTokenSymbol;
    }

    set toTokenSymbol(symbol: string) {
        if (symbol === this.fromTokenSymbol) {
            this.flipTokens();
            return;
        }
        this._toTokenSymbol = symbol;
    }

    get toTokenSymbol(): string {
        return this._toTokenSymbol;
    }

    // gasPriceBN: BigNumber;

    toAmount: string;
    fromAmountBN: BigNumber;
    toAmountBN: BigNumber;

    fromTokenUsdCost: number;
    fromTokenUsdCostView: string;
    toTokenUsdCost: number;
    toTokenUsdCostView: string | undefined;

    tokenAmountInputValidator = [
        Validators.pattern(/^\d*\.{0,1}\d*$/),
        Validators.minLength(0),
        Validators.required
    ];

    swapForm = new FormGroup({
        fromAmount: new FormControl('', this.tokenAmountInputValidator),
        toAmount: new FormControl('', [...this.tokenAmountInputValidator]),
    });

    get fromAmountCtrl(): AbstractControl {
        return this.swapForm.controls.fromAmount;
    }

    get hasErrors(): boolean {
        const errors = this.fromAmountCtrl.errors;
        const isValidToAmount = this.swapForm.controls.toAmount.valid;
        if (!isValidToAmount) {
            return true;
        }
        if (!errors) {
            return false;
        }
        return Object.keys(errors)?.length > 0;
    }

    usdFormatter = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD'
    });

    loading = false;

    sortedTokens$: Observable<ITokenDescriptor[]>;
    public tokenCountInOnePack = 50;

    autoCompleteCtrlFromToken = new FormControl();
    autoCompleteCtrlToToken = new FormControl();
    filteredFromTokens$: Observable<ITokenDescriptor[]>;
    filteredToTokens$: Observable<ITokenDescriptor[]>;

    // gasPrice = '';
    // txSpeedStr = ''

    twitterIcon = faTwitter;
    youtubeIcon = faYoutube;
    telegramIcon = faTelegramPlane;
    githubIcon = faGithub;

    constructor(
        private oneInchApiService: OneInchApiService,
        private gnosisService: GnosisService,
        private tokenPriceService: TokenPriceService,
        public tokenService: TokenService,
        private ethereumService: EthereumService,
        iconRegistry: MatIconRegistry,
        sanitizer: DomSanitizer
    ) {

        iconRegistry.addSvgIcon('settings', sanitizer.bypassSecurityTrustResourceUrl('assets/settings.svg'));
        iconRegistry.addSvgIcon('swap', sanitizer.bypassSecurityTrustResourceUrl('assets/swap.svg'));

        // need to subscribe before addListener
        this.gnosisService.walletAddress$.subscribe();
        // this.gnosisService.isMainNet$.subscribe(console.log);

        this.sortedTokens$ = this.gnosisService.walletAddress$.pipe(
            switchMap((walletAddress) => {
                return combineLatest([
                    this.tokenService.getSortedTokens(walletAddress),
                    this.tokenService.tokenHelper$
                ]);
            }),
            map(([tokens, tokenHelper]) => {

                this.updateFromAmountValidator(tokenHelper);
                this.openLoader = false;
                return tokens;
            }),
            shareReplay({bufferSize: 1, refCount: true})
        );

        this.filteredFromTokens$ = this.getFilteredTokens(this.autoCompleteCtrlFromToken);
        this.filteredToTokens$ = this.getFilteredTokens(this.autoCompleteCtrlToToken);

        this.swapForm.controls.fromAmount.setValue(this.fromAmount, {emitEvent: false});

        const fromAmountChange$ = this.swapForm.controls.fromAmount.valueChanges.pipe(
            startWith(this.fromAmount),
            debounceTime(200),
            distinctUntilChanged(),
            map((value: string) => ({
                fromAmount: value,
                resetFields: true
            }))
        );

        const fromAmountListener$ = merge(fromAmountChange$, this.updateAmounts.asObservable())
            .pipe(
                switchMap((({fromAmount}) => {
                    return this.setAmounts(fromAmount).pipe(
                        // background refresh
                        repeatWhen((completed) => completed.pipe(delay(20000)))
                    );
                }))
            );

        this.subscription.add(fromAmountListener$.subscribe());
        this.gnosisService.addListeners();
    }

    public swap(): void {

        this.loading = true;

        const walletAddress$ = this.gnosisService.walletAddress$;
        const tokenHelper$ = this.tokenService.tokenHelper$;

        const transactions: Tx[] = [];
        let token: ITokenDescriptor;
        let walletAddress: string;
        combineLatest([walletAddress$, tokenHelper$]).pipe(
            switchMap(([addr, tokenHelper]) => {
                walletAddress = addr;
                token = tokenHelper.getTokenBySymbol(this.fromTokenSymbol);
                const toToken = tokenHelper.getTokenBySymbol(this.toTokenSymbol);
                const isTokenApproved$ = this.ethereumService.isTokenApproved(
                    token.address,
                    walletAddress,
                    environment.TOKEN_SPENDER,
                    this.fromAmountBN
                );
                return forkJoin({
                    isApproved: isTokenApproved$,
                    fromToken: of(token),
                    toToken: of(toToken)
                });
            }),
            switchMap(({isApproved, fromToken, toToken}) => {

                if (!isApproved) {
                    const tx: Tx = {
                        to: token.address,
                        data: this.ethereumService.getApproveCallData(environment.TOKEN_SPENDER, ethers.constants.MaxUint256),
                        value: '0'
                    };
                    transactions.push(tx);
                }

                return this.oneInchApiService.getSwapData$(
                    fromToken.address,
                    toToken.address,
                    this.fromAmountBN.toString(),
                    walletAddress,
                    this.slippage,
                    true
                );
            }),
            tap((data: SwapData) => {

                const tx: Tx = {
                    to: data.tx.to,
                    value: data.tx.value,
                    data: data.tx.data,
                    gasPrice: data.tx.gasPrice
                };
                transactions.push(tx);

                this.gnosisService.sendTransactions(transactions);
                this.loading = false;
            }),
            catchError((e) => {
                this.loading = false;
                console.log(e);
                return of('');
            }),
            take(1),
        ).subscribe();
    }

    ngOnDestroy() {
        this.gnosisService.removeListeners();
        this.subscription.unsubscribe();
    }

    private setAmounts(value: string): Observable<any> {

        this.resetToTokenAmount();
        this.fromAmount = value;
        this.loading = true;
        return this.tokenService.tokenHelper$.pipe(
            switchMap((tokenHelper) => {

                const fromToken = tokenHelper.getTokenBySymbol(this.fromTokenSymbol);
                const toToken = tokenHelper.getTokenBySymbol(this.toTokenSymbol);
                const cost$ = this.getTokenCost(fromToken, +value).pipe(
                    map(({tokenUsdCost, tokenUsdCostView}) => {

                        this.fromTokenUsdCost = tokenUsdCost;
                        this.fromTokenUsdCostView = tokenUsdCostView;
                        return tokenHelper.parseAsset(this.fromTokenSymbol, value);
                    }),
                    take(1)
                );
                return forkJoin({
                    fromToken: of(fromToken),
                    toToken: of(toToken),
                    valueBN: cost$
                });
            }),
            switchMap(({valueBN, fromToken, toToken}) => {

                this.fromAmountBN = valueBN;
                return this.oneInchApiService.getQuote$(
                    fromToken.address,
                    toToken.address,
                    this.fromAmountBN.toString()
                );
            }),
            switchMap((quote: Quote) => {

                this.toAmountBN = new BigNumber(quote.toTokenAmount);
                return this.tokenService.tokenHelper$.pipe(
                    switchMap((tokenHelper) => {

                        const token = tokenHelper.getTokenBySymbol(this.toTokenSymbol);
                        const formattedAsset = tokenHelper.formatUnits(this.toAmountBN, token.decimals);
                        this.toAmount = formattedAsset;

                        return this.getTokenCost(token, +formattedAsset).pipe(
                            map(({tokenUsdCost, tokenUsdCostView}) => {

                                this.toTokenUsdCost = tokenUsdCost;
                                this.toTokenUsdCostView = tokenUsdCostView;
                                return formattedAsset;
                            }),
                            take(1)
                        );
                    })
                );
            }),
            tap((toAmount: string) => {

                this.swapForm.controls.toAmount.setValue(toAmount);
                this.loading = false;
            })
        );
    }

    private getFilteredTokens(form: FormControl): Observable<ITokenDescriptor[]> {

        return combineLatest([
            this.sortedTokens$,
            form.valueChanges.pipe(
                startWith('')
            ),
        ]).pipe(
            map((x) => {
                const [tokens, filterText] = x;
                return filterTokens(tokens, filterText);
            })
        );
    }

    private getTokenCost(
        token: ITokenDescriptor,
        tokenAmount: number
    ): Observable<TokenCost> {

        return this.tokenPriceService.getUsdTokenPrice(
            token.address,
            token.decimals
        ).pipe(
            map((priceBN: BigNumber) => {

                const usdPrice = bnToNumberSafe(priceBN) / 1e8;
                return this.calcTokenCost(tokenAmount, usdPrice);
            }),
            take(1)
        );
    }

    private calcTokenCost(tokenAmount: number, tokenPrice: number): TokenCost {
        try {
            const tokenUsdCost = tokenAmount * tokenPrice;
            const tokenUsdCostView = this.usdFormatter.format(tokenUsdCost);
            return {tokenUsdCost, tokenUsdCostView};
        } catch (e) {
            return {tokenUsdCost: 0, tokenUsdCostView: '0'};
        }
    }

    private resetToTokenAmount(): void {
        this.swapForm.controls.toAmount.reset();
        this.toTokenUsdCostView = undefined;
    }

    public onTokenChange(): void {
        this.resetToTokenAmount();
        this.tokenService.tokenHelper$.pipe(
            tap((tokenHelper) => {

                const token = tokenHelper.getTokenBySymbol(this.fromTokenSymbol);
                this.swapForm.controls.fromAmount.setValue(tokenHelper.toFixedSafe(this.fromAmount, token.decimals), {emitEvent: false});
                this.fromAmountBN = tokenHelper.parseUnits(this.fromAmount, token.decimals);
                this.updateAmounts.next({
                    fromAmount: this.fromAmount
                });
                this.tokenAmountInputValidator.pop();
                this.updateFromAmountValidator(tokenHelper);
            }),
            take(1)
        ).subscribe();
    }

    public flipTokens(): void {
        const fts = this._fromTokenSymbol;
        this._fromTokenSymbol = this._toTokenSymbol;
        this._toTokenSymbol = fts;
        this.fromAmount = this.toAmount;
        this.swapForm.controls.fromAmount.setValue(this.fromAmount, {emitEvent: false});
        this.fromTokenUsdCost = this.toTokenUsdCost;
        this.fromTokenUsdCostView = this.toTokenUsdCostView;
        this.onTokenChange();
    }

    public setMaxAmount(fromToken: ITokenDescriptor): void {
        this.swapForm.controls.fromAmount.setValue(fromToken.formatedTokenBalance);
    }

    public getTokenLogoImage(token: ITokenDescriptor): string {
        return token.logoURI || 'https://etherscan.io/images/main/empty-token.png';
    }

    get fromToDiffInPercent() {

        const diff = this.fromTokenUsdCost - this.toTokenUsdCost;
        if (!this.fromTokenUsdCost || +(diff.toFixed(2)) <= 0) {
            return '';
        }

        const percent = Math.abs((diff / this.fromTokenUsdCost) * 100);
        return `( -${percent.toFixed(2)}% )`;
    }

    private updateFromAmountValidator(tokenHelper: TokenHelper): void {
        const token = tokenHelper.getTokenBySymbol(this.fromTokenSymbol);
        const newValidatorFn = maxBn(tokenHelper, token.balance, token.decimals);
        this.tokenAmountInputValidator.push(newValidatorFn);
        this.swapForm.controls.fromAmount.setValidators(this.tokenAmountInputValidator);
        this.swapForm.controls.fromAmount.updateValueAndValidity();
        this.swapForm.controls.fromAmount.markAllAsTouched();
    }

    // onGasPriceChange(x: any): void {
    //   const {gasPriceBN, gasPrice, txSpeed} = x;
    //   this.txSpeedStr = txSpeed
    //   this.gasPrice = gasPrice;
    //   this.gasPriceBN = gasPriceBN;
    // }
}