如何从指令行为中排除特殊情况?

问题描述 投票:4回答:1

我正在尝试修复在页面上搜索时遇到的错误。我有一个可以在所有设置中进行搜索的组件,例如:

Search settings component

[一切正常,搜索返回了应该的值,但是当我删除搜索条件时,我注意到该条件的第一个字母仍在显示并且不会消失,即使搜索设置字段为空的,就像这样:

Avatar string with A selected

检查了两个小时的代码后,我可以看到代码中的问题所在,但我不知道如何解决。

这是我组件的html:

<mat-form-field appearance="standard">
      <input matInput
             pageSearch
             placeholder="{{'searchSettings'|translate}}">
    </mat-form-field>

如您所见,我正在使用一个名为pageSearch的指令,该指令的定义如下,其中包含一个方法valueChange,该方法在每次释放键盘键时都会执行:

ngAfterViewInit() {
    const subscription = this.router.events
      .pipe(filter(e => e instanceof NavigationStart))
      .subscribe(event => {
          if (event) {
            this.pageSearchService.term.next('');
          }
        }
      );
    this.subscriptionsManager.add(subscription);
  }

@HostListener('keyup')
  valueChange() {
    this.pageSearchService.term.next(
      this.elementRef.nativeElement.value
    );
  }

此指令使用pageSearchService,定义如下:

@Injectable()
export class PageSearchService {
  /**
   * Current search term.
   */
  term: BehaviorSubject<string>;
  /**
   * Event to emit when visibility should change in the searchable.
   */
  searchableMatch: EventEmitter<any> = new EventEmitter<any>();

  constructor() {
    this.term = new BehaviorSubject('');
  }
}

我有点想法,问题可能是它总是期望一个next()值,当它为null时,它不会运行,但是它拥有的最后一个值仍然冻结在其中。

我曾尝试更改指令中的方法valueChange,但是每次最终关闭对BehaviorSubject的订阅时,这些是我尝试过的事情:

  1. 添加条件以检查字符串是否为空并且不调用BehaviorSubject
valueChange() {
    if (this.elementRef.nativeElement.value !== '') {
      this.pageSearchService.term.next(
        this.elementRef.nativeElement.value
      );
    }
  }

它没有用,我也尝试过退订并再次订阅,但是也没有用

valueChange() {
    if (this.elementRef.nativeElement.value !== '') {
      this.pageSearchService.term.next(
        this.elementRef.nativeElement.value
      );
    } else {
      this.pageSearchService.term.unsubscribe();
      this.pageSearchService.term._subscribe(this.elementRef.nativeElement.value);
    }
  }

它给我这个错误:

Error when unsubscribing

所以现在我不知道该怎么办。在给出字符串''的情况下,我如何要求该指令不执行特定的操作?

searchableMatch EventEmitter由其他3个指令使用,如下所示:

The SearchNoResultsDirective:

export class SearchNoResultsDirective implements AfterViewInit, OnDestroy {
  @Input('searchNoResults') sectionsId: string[];
  subscriptionsManager: Subscription = new Subscription();
  visibility: {
    term: string,
    visible: boolean
  } = {
    term: '',
    visible: true
  };

  constructor(private elementRef: ElementRef,
              private renderer: Renderer2,
              private pageSearchService: PageSearchService) {
  }

.
.
.

  ngAfterViewInit() {
    const subscription = this.pageSearchService.searchableMatch.subscribe(match => {
      if (this.sectionsId.indexOf(match.sectionId) >= 0 ) {
        this.update({
          term: match.term,
          visible: match.visible
        });
      }
    });
    this.subscriptionsManager.add(subscription);
  }
}

The SearchableSectionDirective:

export class SearchableSectionDirective extends BaseClass implements AfterViewInit {
  @Input('searchableSection') sectionId: string;

.
.
.

  ngAfterViewInit() {
    const subscription = this.pageSearchService.searchableMatch.subscribe(match => {
      if (match.sectionId === this.sectionId) {
        this.update({
          term: match.term,
          visible: match.visible
        });
      }
    });
    this.subscriptionsManager.add(subscription);
  }
}

和SearchableDirective:

export class SearchableDirective implements AfterViewInit, OnDestroy {
  @Input('searchable') sectionId: string;
  @Input() highlightColor = '#FFF176';
  match: EventEmitter<any> = new EventEmitter<any>();
  subscriptionsManager: Subscription = new Subscription();
  originalText: string;

  ngAfterViewInit() {
    this.originalText = this.elementRef.nativeElement.innerText;
    this.subscriptionsManager.add(
      this.pageSearchService.term.subscribe(term => this.checkIfMatch(term))
    );
  }

  checkIfMatch(val: string) {
    let match = false;
    let clean = false;
    if (val) {
      const startInd = this.originalText.toLowerCase().indexOf(val.trim().toLowerCase());
      if (startInd > -1) {
        match = true;
        const startText = this.render.createText(this.originalText.slice(0, startInd));
        const matchText = this.render.createText(this.originalText.slice(startInd, startInd + val.trim().length));
        const endText = this.render.createText(this.originalText.slice(startInd + val.trim().length, this.originalText.length));

        const matchSpan = this.render.createElement('span');
        this.render.appendChild(
          matchSpan,
          matchText
        );
        this.render.setStyle(
          matchSpan,
          'background',
          this.highlightColor
        );

        this.elementRef.nativeElement.innerHTML = '';

        this.render.appendChild(
          this.elementRef.nativeElement,
          startText
        );
        this.render.appendChild(
          this.elementRef.nativeElement,
          matchSpan
        );
        this.render.appendChild(
          this.elementRef.nativeElement,
          endText
        );
      } else {
        clean = true;
      }
    } else if (this.originalText) {
      clean = true;
    }

    **if (clean) {
      this.elementRef.nativeElement.innerHTML = this.originalText;  <--this is how the solution looks
    }**

    if (this.sectionId) {
      this.pageSearchService.searchableMatch.emit({
        sectionId: this.sectionId,
        term: val,
        visible: match
      });

      this.match.emit({
        term: val,
        visible: match
      });
    }
  }
}

我正在浏览这3个指令,以查看是否找到问题。

angular typescript angular-directive
1个回答
1
投票

我认为唯一的问题是放置逻辑的函数。我认为您只需要添加checkIfMatch

checkIfMatch(val: string) {

    let match = false;
    let clean = false;
    if (val) {

       //func logic

     } else {
        // you need to add else block to the function
        this.elementRef.nativeElement.innerHTML = this.originalText;

     }

}

© www.soinside.com 2019 - 2024. All rights reserved.