美文网首页Angular
Angular与better-scroll 下拉加载数据

Angular与better-scroll 下拉加载数据

作者: zzz1t1 | 来源:发表于2019-11-01 11:26 被阅读0次

    首先安装

    npm install -save better-scroll
    

    在angular里面创建一个scroll的组件

    ng g c scroll-layout
    

    ScrollLayout.component.html

    <div class="scroll" #scroll style="overflow: hidden;">
      <ng-content (click)="loadData(true)"></ng-content>
    </div>
    

    ScrollLayout.component.ts

    import { Component, OnInit, ViewChild, ElementRef, Output, EventEmitter, Input } from '@angular/core';
    import BScroll from 'better-scroll';
    
    @Component({
      selector: 'app-scroll-layout',
      templateUrl: './scroll-layout.component.html',
      styleUrls: ['./scroll-layout.component.scss']
    })
    export class ScrollLayoutComponent implements OnInit {
    
      scroll;
      @Input() height: number;
      @ViewChild('scroll') scrollEl: ElementRef;
      @Output() loadData = new EventEmitter<boolean>();
    
      constructor() { }
    
      ngOnInit() {
        this.scrollInit();
      }
    
    
      scrollInit() {
        // 初始化滚动对象
        this.scrollEl.nativeElement.style.height = `${this.height}px`;
    
        this.scroll = new BScroll(this.scrollEl.nativeElement, { click: true });
        this.scrollEl.nativeElement.addEventListener('touchend', () => {
          this.scrollEl.nativeElement.style.height = `${this.height}px`;
          this.loadData.emit(true);
        });
      }
    
    }
    

    在scrollInit方法里,初始化当前高度,每次下拉的时候触发计算高度和拉取数据或者其他业务逻辑。

    views视图中的index.component.html

    <div>   
        <div class="container-1">
        <app-scroll-layout (loadData)="onloadData()" [height]="height">
            <ul style="list-style: none;padding: 0;">
                <li class="item" *ngFor="let item of topics; let num = index;">
                    <article class="article">
                        <a [href]='"https://cnodejs.org/api/v1/user/" + item.author.loginname' class="article-img"><img [src]="item.author.avatar_url"></a>
                        <div class="article-text">
                            <span class="article-tag" *ngIf="tabFilter(item)">{{tabFilter(item)}}</span>
                            <a [routerLink]="['/application/detail/' + item.id ]"   [title]="item.title" class="article-title">{{item.title}}</a>
                        </div>
                        <span class="article-time">{{dateFilter(item.last_reply_at)}}</span>
                    </article>
                </li>
            </ul>
        </app-scroll-layout>
        </div>
    </div>
    

    index.components.ts

    import { Component, OnInit, ViewChild, Input } from '@angular/core';
    import { HttpClient, HttpParams } from '@angular/common/http';
    import { ActivatedRoute } from '@angular/router';
    import { ScrollLayoutComponent } from '../../components/scroll-layout/scroll-layout.component';
    
    @Component({
      selector: 'app-application-index',
      templateUrl: './application-index.component.html',
      styleUrls: ['./application-index.component.scss']
    })
    export class ApplicationIndexComponent implements OnInit {
    
      init;
      height: number;
      str: string;
      topics = [];
      params = {
        page: 1,
        limit: 12,
        tab: 'all',
      };
    
      @ViewChild('scroll') scrollLayoutComponent: ScrollLayoutComponent;
    
      constructor(
        private http: HttpClient,
        private route: ActivatedRoute,
        ) { }
    
      ngOnInit() {
        this.init = this.route.queryParams.subscribe(params => {
          this.params.tab = !params.tab ? this.params.tab : params.tab;
          this.getTopics();
        });
      }
    
      getTopics(onload?) {
        this.http.get('https://cnodejs.org/api/v1/topics', {params: JSON.parse(JSON.stringify(this.params))}).subscribe(res => {
          if (res['success'] === true) {
            res['data'] && res['data'].forEach(element => {
              this.topics.push(element);
            });
            this.height = res['data'].length > 0 ? res['data'].length * 77 : 0;
            this.str = res['data'] === [] && onload ? '已经到底啦~' : '';
          }
        });
      }
    
      onloadData() {
        this.params.page = this.params.page + 1;
        this.getTopics(1);
      }
    
      tabFilter(item) {
        if (item && item.top === true) {
          return '置顶';
        } else if (item.good === true) {
          return '精华';
        } else {
          return '';
        }
      }
    
    
      dateFilter(val) {
        const now = new Date().getTime() / 1000;
        const currentTime = Date.parse(val) / 1000;
        const milliseconds = (now - currentTime) ;
        if (milliseconds <=  60 * 1) {
          return '几秒前';
        } else if ( milliseconds && milliseconds <=  60 * 60) {
          return Math.round((milliseconds / ( 60))) + '分钟前';
        } else if ( milliseconds && milliseconds <=  60 * 60 * 24) {
          return Math.round(milliseconds / ( 60 * 60)) + '小时前';
        } else {
          return Math.round(milliseconds / ( 60 * 60 * 24)) + '天前';
        }
      }
    
      navChange(val) {
        switch (val.tab) {
          case 'share': return '分享';
          case 'ask': return '问答';
          case 'job': return '招聘';
          case 'good': return '精华';
          default: return '全部';
        }
      }
    
    }
    

    getTopics方法里面判断当前每个<li>的高度(代码里面暂时写死的)
    每次触发下拉动作的时候,ScrollLayout组件里面会触发下拉的条件,去计算高度和加载数据

    相关文章

      网友评论

        本文标题:Angular与better-scroll 下拉加载数据

        本文链接:https://www.haomeiwen.com/subject/csrfbctx.html