Рефакторинг длинной функции в отдельный файл - PullRequest
0 голосов
/ 30 октября 2019

У меня есть угловое приложение с некоторыми функциями поиска и некоторыми переключателями. И у меня есть функция, которая становится «очень» большой. Поэтому я переместил эту функцию в отдельный файл. Но теперь переключатели больше не работают.

Итак, компонент выглядит так:

export class ExtendedSearchComponent implements OnInit, OnChanges {

//And here I had this function: 

  setSelectedSearchOptions(optionLabel: string) {

    this.filterSelectedSearchOptios; 
    this.selectedOption = optionLabel;
    this.selectedSearch = optionLabel;

    if (optionLabel === 'Registratie') {
       this.showDatePickerOne = true;
      this.showDatePickerTwo = false;
      this.showDatePickerThree = false;
      this.buttonFilterDisabled = false;
      this.startDate = undefined;
      this.selectedValue = '';
      this.showDropdownChallenge = false;
      this.showDropdownVcheqCode = false;
      this.showDropdownMeasurement = false;
      this.showDropdownIndicator = false;
    }

    if (optionLabel === 'Vcheq') {
      this.showDatePickerOne = true;
      this.showDatePickerTwo = false;
      this.showDatePickerThree = false;
      this.showDropdownMeasurement = false;
      this.isButtonVisible = true;
      this.startDate = undefined;
      this.showDropdownVcheqCode = true;
      this.showDropdownChallenge = false;
      this.showDropdownQrCode = false;
      this.showDropdownIndicator = false;

    }

    if (optionLabel === 'Doelen') {
      this.showDatePickerOne = true;
      this.showDatePickerTwo = false;
      this.showDatePickerThree = false;
      this.showDropdownMeasurement = false;
      this.isButtonVisible = false;
      this.startDate = undefined;
      this.selectedValue = ',';
      this.selectedValueOptie = ',';
      this.selectedValueProgressie = ',';
      this.showDropdownQrCode = true;
      this.showDropdownChallenge = false;
      this.showDropdownVcheqCode = false;
      this.showDropdownIndicator = false;

    }
  }

}

, а шаблон компонента выглядит так:

<form class="from-horizontal" #form="ngForm" [formGroup]="filterSection" (ngSubmit)="closeSearch(form)">
  <div class="filter-plus mat-elevation-z8" [ngClass]="{ expanded: searchExpanded }">
    <div class="filter-plus-search-fields">
      <div class="search-types">
        <mat-radio-group>
          <mat-radio-button
            *ngFor="let option of this.filterListData.searchOptions; let i = index"
            [value]="i"
            [checked]="i === 0"
            [(value)]="option"
            (change)="this.filterSelectedSearchOptios.setSelectedSearchOptions(option.label)"
          >
            {{ option.label }}
          </mat-radio-button>
        </mat-radio-group>
      </div>
</form>

Но я переместил эту функцию в отдельный файл, например:


export class filterSelectedSearchOptions{


  showDropdownQrCode = false;
  showDropdownChallenge = false;
  showDropdownVcheqCode = false;
  showDropdownMeasurement = false;
  showDropdownIndicator = false;
  searchExpanded = false;
  submitEnabled = false;
  buttonFilterDisabled: boolean;

  selectedSearch = 'Registratie';
  selectedValue: string;
  selectedValueStatus: string;
  selectedValueOptie: string;
  selectedVcheqOption: string;
  selectedQrcode: string;

  selectedValueProgressie: string;
  startDate: Date;
  selectedSearchOptions = {};
  isButtonVisible = true;
  isButtonFourVisible = false;
  isButtonFiveVisible = false;
  isButtonMeasurements = false;
  showDatePickerOne = true;
  showDatePickerTwo = true;
  showDatePickerThree = true;
  selectedOption: any = 'Registratie';


   setSelectedSearchOptions(optionLabel: string) {
    //this.filterSection.reset();
    this.selectedOption = optionLabel;
    this.selectedSearch = optionLabel;

    if (optionLabel === 'Registratie') {
       this.showDatePickerOne = true;
      this.showDatePickerTwo = false;
      this.showDatePickerThree = false;
      this.buttonFilterDisabled = false;
      this.startDate = undefined;
      this.selectedValue = '';
      this.showDropdownChallenge = false;
      this.showDropdownVcheqCode = false;
      this.showDropdownMeasurement = false;
      this.showDropdownIndicator = false;
    }

    if (optionLabel === 'Vcheq') {
      this.showDatePickerOne = true;
      this.showDatePickerTwo = false;
      this.showDatePickerThree = false;
      this.showDropdownMeasurement = false;
      this.isButtonVisible = true;
      this.startDate = undefined;
      this.showDropdownVcheqCode = true;
      this.showDropdownChallenge = false;
      this.showDropdownQrCode = false;
      this.showDropdownIndicator = false;

    }

    if (optionLabel === 'Doelen') {
      this.showDatePickerOne = true;
      this.showDatePickerTwo = false;
      this.showDatePickerThree = false;
      this.showDropdownMeasurement = false;
      this.isButtonVisible = false;
      this.startDate = undefined;
      this.selectedValue = ',';
      this.selectedValueOptie = ',';
      this.selectedValueProgressie = ',';
      this.showDropdownQrCode = true;
      this.showDropdownChallenge = false;
      this.showDropdownVcheqCode = false;
      this.showDropdownIndicator = false;

    }
}

, и поэтому у меня теперь компонент выглядит так:


export class ExtendedSearchComponent implements OnInit, OnChanges {


  public filterListData:FilterListData;

 ngOnInit() {

 this.filterSelectedSearchOptios = new filterSelectedSearchOptions();
} 

и шаблон компонентавыглядит теперь так:

<form class="from-horizontal" #form="ngForm" [formGroup]="filterSection" (ngSubmit)="closeSearch(form)">
  <div class="filter-plus mat-elevation-z8" [ngClass]="{ expanded: searchExpanded }">
    <div class="filter-plus-search-fields">
      <div class="search-types">
        <mat-radio-group>
          <mat-radio-button
            *ngFor="let option of this.filterListData.searchOptions; let i = index"
            [value]="i"
            [checked]="i === 0"
            [(value)]="option"
            (change)="this.filterSelectedSearchOptios.setSelectedSearchOptions(option.label)"
          >
            {{ option.label }}
          </mat-radio-button>
        </mat-radio-group>
      </div>
</form>

Но теперь переключатели больше не работают.

Так что мой вопрос. Что нужно исправить, чтобы переключатели снова работали с новым созданным файлом: filterSelectedSearchOptions

, а также как я могу реорганизовать функцию: setSelectedSearchOptions?

Спасибо

если я сделаю это:

export class ExtendedSearchComponent extends  FilterSelectedSearchOptions implements OnInit, OnChanges 

 public filterSelectedSearchOptios: FilterSelectedSearchOptions;


 ngOnInit() {


    this.filterSelectedSearchOptios = new FilterSelectedSearchOptions();

}

все равно переключатели не работают. Я не получаю никаких ошибок, но если я выберу переключатель, никаких изменений

Ответы [ 2 ]

0 голосов
/ 30 октября 2019

Значение ключевого слова ' this ' начинает ссылаться на другой объект, который создается при использовании 'new filterSelectedSearchOptions ();'стоимость. Поэтому лучше использовать следующий синтаксис в файле component.ts:

    this.filterSelectedSearchOptios = filterSelectedSearchOptions;

(где ссылка на RHS получается с помощью импорта из файла seperate , где у вас естьэкспортировал filterSelectedSearchOptions class)

0 голосов
/ 30 октября 2019

В вашем рефакторированном коде this обратитесь к другому классу, и он не будет работать в вашем компоненте. Так что вы можете использовать вместо него inheritance. Так что переместите свой код в другой файл и extands ваш класс компонента, например,

export class ExtendedSearchComponent extends filterSelectedSearchOptions implements OnInit, OnChanges  {

не нужно менять HTML

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...