角;通过 rxjs

问题描述 投票:0回答:0

我有这个 Angular 代码在 html 中生成列表项:

<div *ngFor="let category of categoryList; let i = index" class="swiper-slide">
                          <div #fb class="client-item" (click)="openProductPage(category)" (mouseenter)="categoryEnter(i)" (mouseleave)="leave()"   >
                              
                            <div fxFlex="100" fxFlex.gt-sm="100" fxFlex.sm="100" ngClass.xs="pt-5" > 
                                <p fxLayout="row" fxLayoutAlign="start center" class="mt-1" >
                                    <mat-spinner [strokeWidth]="selectedCategoryForMenu === category && !isLoadingDone ? 3: 0" [diameter]="100" 
                                    [ngStyle]="{'background-image': 'url(' + 'http://localhost:5555' + category.image.urls[0] + ')', 'background-position': 'center',
                                       'background-repeat': 'no-repeat',
                                       'background-size': '100%'}"
                                    ></mat-spinner>
                                </p>                              
                                <p fxLayout="row" fxLayoutAlign="center"  class="mt-1">
                                    <span class="show-title">
                                        {{category.userTitle}}
                                    </span>
                                </p>                               
                            </div>
                          </div>
                      </div>

如代码所示,当用户将鼠标指针输入该区域时

categoryEnter
事件触发,其主体如下:

categoryEnter( index: number) {
  this.fbButtons.toArray().forEach((tr, i)=> {
    const leave$ = fromEvent(tr.nativeElement, "mouseleave");
    fromEvent(tr.nativeElement, 'mouseenter').pipe(takeUntil(leave$), debounceTime(1000))
    .subscribe((e: MouseEvent) => {
        if(index === i) {
          console.log(e, this.categoryList[i].userTitle);
        }
        
    });
  });
}

函数使用

fbButtons
,它是
QueryList
ElementRef
。问题是每次鼠标进入一个项目
mouseenter
事件都会比上一次多调用一次。例如

At first time:  Item1 -> mouseenter.
At second time: Item1 -> mouseenter
                Item1 -> mouseenter
At third time:  Item1 -> mouseenter
                Item1 -> mouseenter
                Item1 -> mouseenter
angular rxjs
© www.soinside.com 2019 - 2024. All rights reserved.