angular-redux Подписаться на хранилище с помощью оператора @Select и назначить его переключателю - PullRequest
0 голосов
/ 29 ноября 2018

Я добавляю иконку FAB в свое приложение, используя Angular 4. Я впервые пишу для него редукционные действия и редуктор.Но я не могу понять, как подписаться на магазин с помощью оператора @select и назначить его методу переключения (открыть / закрыть). Поэтому, если он получит ложное значение из магазина, он будет закрыт, но если он его откроет »открою кнопку.Я использую этот пример Fab Button

Настроил немного fab.component.ts:

import {
  Component,
  Input,
  ContentChildren,
  ContentChild,
  ElementRef,
  HostListener,
  AfterContentInit,
} from '@angular/core';

import { FabToggleComponent } from './fab-toggle/fab-toggle.component';
import { FabButtonComponent } from './fab-button/fab-button.component';

import { select } from '@angular-redux/store';
import { FabButtonActions } from '../../store/fab/store/actions';

@Component({
  selector: 'be-fab',
  templateUrl: './fab.component.html',
  styleUrls: ['./fab.component.css'],
})
export class FabComponent implements AfterContentInit {
  @Input() dir = 'right';
  @ContentChild(FabToggleComponent) toggle;
  @ContentChildren(FabButtonComponent) buttons;
  @select('fabButtonState') fabStates$;

  private activeBtn: any;
  private element: any;
  private fabStateAfterBtnClick: any;
  constructor(element: ElementRef, private fabButtonActions: FabButtonActions) {
    this.element = element.nativeElement;
  }
  get active() {
    return this.activeBtn;
  }

  set active(val) {
    this.updateButtons(val);
    this.activeBtn = val;
    this.fabStateAfterBtnClick = this.fabStates$.subscribe(fabState => {
      console.log(fabState);
      // if (fabState) {
      //   this.fabButtonActions.openFabMenu();
      // } else {
      //   this.fabButtonActions.closeFabMenu();
      // }
    });
  }


  ngAfterContentInit() {
    setTimeout(() => {
      this.toggle.onClick.subscribe(() => {
        this.active = !this.active;
      });
    }, 1000);
  }

  getTranslate(idx) {
    if (this.dir === 'right') {
      return `translate3d(${60 * idx}px,0,0)`;
    } else if (this.dir === 'up') {
      return `translate3d(0,${-60 * idx}px,0)`;
    } else {
      console.error(`Unsupported direction for Fab; ${this.dir}`);
    }
  }

  updateButtons(active) {
    let idx = 1;
    for (let btn of this.buttons.toArray()) {
      let style = btn.element.nativeElement.style;
      style['transition-duration'] = active ? `${90 + 100 * idx}ms` : '';
      style['transform'] = active ? this.getTranslate(idx) : '';
      idx++;
    }
  }

  @HostListener('document:click', ['$event.target'])
  onDocumentClick(target) {
    if (this.active && !this.element.contains(target)) {
      this.active = false;
    }
  }
}

export const FAB_COMPONENTS = [
  FabToggleComponent,
  FabButtonComponent,
  FabComponent,
];

Вот мой метод подписки:

this.fabStateAfterBtnClick = this.fabStates $ .subscribe (fabState => {console.log (fabState); // if (fabState) {// this.fabButtonActions.openFabMenu (); //} else {// this.fabButtonActions.closeFabMenu (); //}});

fab-button.actions.ts выглядит следующим образом

import { Injectable } from '@angular/core';
import { NgRedux } from '@angular-redux/store';
import { IAppState } from '../../../../store/app-state.type';
import {
    AppConfigService,
    UIService,
} from '../../../../core/';

import { Subscription } from 'rxjs/Subscription';

/** This actions is used to start and stop the polling for the component
 * that needs to dispatch those actions
 *
 * @example
 *
 * fabButtonActions
 *
 */
@Injectable()
export class FabButtonActions {
    /* *
      * For Redux
      * Use this manage the ACTIONS of the reducer
    */
    static readonly ACTIONS = {
        OPEN: 'OPEN',
        CLOSE: 'CLOSE',
    };
    /* * @constructor
       *
       * initializes the FabButtonActions
       * initializes the NgRedux<IAppState>
    * */
    constructor(private ngRedux: NgRedux<IAppState>) { }
    /* *
    * Dispatches action to fab button reducer
    * to open the
    */
    openFabMenu() {
        this.ngRedux.dispatch({
            type: FabButtonActions.ACTIONS.OPEN,
        });
    }
    closeFabMenu() {
        this.ngRedux.dispatch({
            type: FabButtonActions.ACTIONS.CLOSE,
        });
    }
}

fab-button.reducer.ts выглядит следующим образом

import { Reducer } from 'redux';
import { FabButtonActions } from '../actions';

export interface FabButtonState {
  isFabOpen: boolean;
}

export const initialFabButtonState: FabButtonState = {
  isFabOpen : true,
};

export const fabButtonReducer: Reducer<FabButtonState> = (
  state = initialFabButtonState,
  action,
) => {
  switch (action.type) {
    case FabButtonActions.ACTIONS.OPEN:
      return {
        ...state,
        isFabOpen: true,
      };
    case FabButtonActions.ACTIONS.CLOSE:
      return {
        ...state,
        isFabOpen: false,
      };
    default:
      return state;
  }
};

Пожалуйста, помогите мне с методом подписки.все, что я пытался, это подчеркивало.спасибо.

...