【问题标题】:Angular - scroll to the bottom of the page causes one function callAngular - 滚动到页面底部会导致一个函数调用
【发布时间】:2021-04-21 12:56:31
【问题描述】:

我想在我的网站上制作类似于 Instagram 等知名网站的解决方案, 当用户滚动页面并到达页面底部时,会发送另一个请求并从 API 加载另一张照片。

我的代码:

  @HostListener('window:scroll', ['$event'])
  getScrollHeight(): void {
    if (document.body.scrollTop + window.innerHeight >= document.body.scrollHeight) {
      console.log('yes');
      this.pageNumber += 1;
      this.fetchData(this.pageNumber); //1
    }
  }

因为在if 语句中有一个符号>= 这会返回true 多次并且方法this.fetchData() 也被多次调用但我只需要一个 当我将 >= 更改为 === 时,有时它不是真的(它会改变我滚动的速度)

有什么办法吗?

工作回购:https://stackblitz.com/edit/angular-bottom-of-the-page

【问题讨论】:

    标签: html angular


    【解决方案1】:

    有几种不同的方法可以解决这个问题。最有可能的是,鉴于您共享的代码,最直接的方法是利用跟踪“加载”状态的属性。您的 stackblitz 示例未显示您问题中的 fetchData 方法。我在下面截取了一个,假设通话延迟为 1 秒。

    我的假设是您的fetchData 调用会加载更多结果,然后使您的页面内容更大,将window.innerHeightwindow.scrollY 向下推,这样当页面底部为达到了第二次。

    当你去获取更多数据时isLoading属性设置为true,然后在接收到新数据时设置为false。这将允许事件发生多次,但应等到第一个事件完成后再触发另一个事件。

        @Component({
          selector: "my-app",
          templateUrl: "./app.component.html",
          styleUrls: ["./app.component.css"]
        })
        export class AppComponent {
          name = "Angular " + VERSION.major;
        
          pageNumber = 1;
        
          isLoading = false;
          @HostListener("window:scroll", ["$event"])
          getScrollHeight(): void {
            if (window.innerHeight + window.scrollY >= document.body.offsetHeight && !this.isLoading) {
              console.log("bottom of the page");
              this.pageNumber += 1;
              this.isLoading = true;
              this.fetchData()
                  .pipe(
                    tap(() => this.isLoading = false)
                  )
                  .subscribe();
            }
          }
        
          fetchData() {
            return of('foo')
                    .pipe(delay(1000));
          }
        }
    

    另一种方法是使用Intersection Observer API

    【讨论】:

      【解决方案2】:

      我认为您正在寻找的是一个名为无限滚动的功能。在 stackoverflow 中有一些关于这个主题的讨论。一些选项在how to implement infinite scroll pagination using ngx-infinite-scroll without ngx-infinite-scroll 上进行讨论。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-14
        • 2012-07-27
        • 1970-01-01
        • 2014-06-10
        相关资源
        最近更新 更多