Angular 中的相交观察者 [英] Intersection observer in Angular

查看:23
本文介绍了Angular 中的相交观察者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Angular 中设置 IntersectionObserver 但我无法让它工作.当我使用 HttpClient 从服务器向下滚动时,我想加载数据.我正在做这样的事情:在页面底部的 HTML 中,我有这个:

在 .ts 文件中,我使用 ViewChild 获取元素并将其传递给 IntersectionObserverService:

@ViewChild('ob') ob: ElementRef;构造函数(私人内部:IntersectionObserverService) { }ngAfterViewInit(): 无效 {this.inter.createAndObserve(this.ob);}

然后在服务中,我观察传入的元素并尝试 console.log 条目,但什么也没发生.

@Injectable({提供在:'根'})导出类 IntersectionObserverService {_observer: IntersectionObserver |不明确的;构造函数(){}createAndObserve(元素:ElementRef){常量选项 = {根:空,阈值:0.1};this._observer = new IntersectionObserver((条目,观察者)=> {console.log('on')entry.forEach((entry: IntersectionObserverEntry) => {控制台日志(条目);console.log('ok');//观察者.unobserve(entry.target);});}, 选项);this._observer.observe(element.nativeElement);}}

当我与 <div #ob></div> 相交时,我希望在这里传递一个回调以从后端获取我的数据.然后向前传递.如何让 IntersectionObserver 观察它并显示条目?

解决方案

在你的组件中:

@ViewChild('ob', { read: ElementRef })ob:元素引用;ngAfterViewInit(): 无效 {this.inter.createAndObserve(this.ob).pipe(filter((isVisible: boolean) => isVisible),switchMap(() => this.yourService.loadData())).subscribe(data => { ... });}

然后转到您的服务并更新您的方法,因此现在它将返回一个可观察的对象,该可观察对象每次与您的宿主元素相交时都会发出一个布尔事件:

createAndObserve(element: ElementRef): Observable{返回新的 Observable(观察者 => {const intersectionObserver = 新的 IntersectionObserver(条目 => {观察者.下一个(条目);});crossObserver.observe(element.nativeElement);返回 () =>{intersectionObserver.disconnect();};}).管道(合并地图((条目:IntersectionObserverEntry[])=>条目),地图(条目 => entry.isIntersecting),distinctUntilChanged());}

I am trying to set up IntersectionObserver in Angular but I can't get it to work. I want to load data when I scroll down using HttpClient from the server. I'm doing something like this: In HTML on the bottom of the page I have this:

<div #ob></div>

In the .ts file I am using ViewChild to grab the element and pass it to the IntersectionObserverService:

@ViewChild('ob') ob: ElementRef;

constructor(
    private inter: IntersectionObserverService) { }

 ngAfterViewInit(): void {
    this.inter.createAndObserve(this.ob);
  }

Then in the service I observe the passed in element and try to console.log the entries but nothing is happening.

@Injectable({
    providedIn: 'root'
})
export class IntersectionObserverService {
    _observer: IntersectionObserver | undefined;

    constructor() { }

    createAndObserve(element: ElementRef) {
        const options = {
            root: null,
            threshold: 0.1
        };

        this._observer = new IntersectionObserver((entries, observer) => {
            console.log('on')
            entries.forEach((entry: IntersectionObserverEntry) => {
                console.log(entry);
                console.log('okk');
                // observer.unobserve(entry.target);
            });
        }, options);
        this._observer.observe(element.nativeElement);
    }

}

I would want here to pass a callback to get my data from the backend when I intersect <div #ob></div>. Then pass it forward. How can I make the IntersectionObserver to observe it and display entries?

解决方案

In your component do:

@ViewChild('ob', { read: ElementRef })
ob: ElementRef;

ngAfterViewInit(): void {
  this.inter.createAndObserve(this.ob).pipe(
    filter((isVisible: boolean) => isVisible),
    switchMap(() => this.yourService.loadData())
  ).subscribe(data => { ... });
}

Then go to your service and update your method, so now it will return an observable that will emit a boolean event everytime you intersect your host element:

createAndObserve(element: ElementRef): Observable<boolean> {
  return new Observable(observer => {
    const intersectionObserver = new IntersectionObserver(entries => {
      observer.next(entries);
    });

    intersectionObserver.observe(element.nativeElement);

    return () => { intersectionObserver.disconnect(); };
  }).pipe(
    mergeMap((entries: IntersectionObserverEntry[]) => entries),
    map(entry => entry.isIntersecting),
    distinctUntilChanged()
  );
}

这篇关于Angular 中的相交观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆