如何在Angular4的同一视图中使用ngx分页实现多个分页?

时间:2017-10-04 06:25:36

标签: angular typescript angular-cli

Iam在angular4中进行分页。我使用ngx分页来实现分页过程。我需要根据用户选择的类型应用分页。如果用户选择类别,我需要显示带分页的分类数据,默认情况下在页面上加载,我需要用分页显示所有数据。这是因为Iam面临问题,因为分页只适用于类别数据。我的代码是:

import { Component, OnInit } from '@angular/core';
import {Http,Response,Headers, RequestOptions} from '@angular/http';
import { Router} from '@angular/router';
import * as _ from "lodash";
import { PaginationService } from '../../pagination.service';
import { WooApiService } from 'ng2woo';
import {SearchFilterPipe} from '../../search-filter.pipe'
@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
visible:boolean=false;
visibleCategory:boolean=true;
  public productsList=[];
public categories=[];
public categoryList=[];
catId:Number;
    public objArray: Array<string> = ["Albania", "Andorra", "Armenia", "Austria", "Azerbaijan"];
total:any;  
    currentPage:Number;
constructor(private http:Http,private router:Router,private woo: WooApiService) { 
    this.getCategories();
  }
createAuthorizationHeader(headers: Headers) {
    headers.append('Authorization', 'Basic ' +
      btoa('ck_543700d9f8c08268d75d3efefb302df4fad70a8f:cs_f1514261bbe154d662eb5053880d40518367c901')); 
    headers.append("Content-Type", "application/json");
  }   
    getData(){

     let headers = new Headers();
     this.createAuthorizationHeader(headers);
return this.http.get("https://www.colourssoftware.com/wordpress/wp-json/wc/v2/products?page=1&per_page=10",{
        headers:headers
        })
      .subscribe(data => { 
        const products=data.json();
          console.log(data.headers);

     this.total = data.headers.get('X-WP-TotalPages');
    console.log("Pages ",this.total);

           for( var i=1;i<=this.total;i++){
    console.log("hello "+this.total);
    this.getProducts(i);
    }   
    },
err => {
    console.log("Error!: ",err);
}
        );
       

    }   
getProducts(i){ 
    this.visibleCategory=true;
    this.visible=false;
    this.currentPage=i;
    console.log("cpage "+this.currentPage);
    let headers = new Headers();
    this.createAuthorizationHeader(headers);
return this.http.get("https://www.colourssoftware.com/wordpress/wp-json/wc/v2/products?per_page=10&page="+this.currentPage,{
        headers:headers
        })
      .subscribe(data => { 
          const products = data.json();
for(var k=0;k<products.length;k++){
    this.productsList.push(products[k]);
    }
          console.log("hello"+JSON.stringify(this.productsList));
        },
err => {
    console.log("Error!: ",err);
}
        ); 

 } 
       getCategories(){
   console.log('categories');
    let headers=new Headers();
    this.createAuthorizationHeader(headers);
   return this.http.get('https://www.colourssoftware.com/wordpress/wp-json/wc/v2/products/categories',{
       headers:headers
       })
     .subscribe(data => { 
       const category=data.json();
       console.log(category);
         this.categories=category;
         console.log(JSON.stringify(this.categories));
       },
err => {
   console.log("Error!: ",err);
}
       );
   }
getCatProducts(id,count){
if(count<=10){
    this.visible=true;
    this.visibleCategory=false;
    this.catId=id;
    console.log("id "+this.catId);
    let headers=new Headers();
    this.createAuthorizationHeader(headers);
   return this.http.get('https://www.colourssoftware.com/wordpress/wp-json/wc/v2/products?category='+this.catId,{
       headers:headers
       })
     .subscribe(data => { 
       const items=data.json();
       console.log(items.length);
         this.categoryList=items;
         console.log(JSON.stringify(this.categoryList.length));
       },
err => {
   console.log("Error!: ",err);
}
       ); 
    }
}
 
product(value){
    this.router.navigate(['productdetails',value]);
}

  ngOnInit() {
      this.getData();  
  }

}
<body>

    <!-- breadcrumbs -->
    <div class="breadcrumbs">
        <div class="container">
            <ol class="breadcrumb breadcrumb1 animated wow slideInLeft" data-wow-delay=".5s">
                <li><a routerLink="/home"><span class="glyphicon glyphicon-home" aria-hidden="true"></span>Home</a></li>
                <li class="active">Products</li>
            </ol>
        </div>
    </div>
    <div class="products">
        <div class="container">
            <div class="col-md-4 products-left">
                <div class="categories animated wow slideInUp" data-wow-delay=".5s">
                    <h3>Categories</h3><br>
                    <ul class="cate" *ngFor="let item of categories">
                        <li><a style="cursor:pointer" (click)="getCatProducts(item.id,item.count)">{{item.name}}</a> <span>({{item.count}})</span></li>
                    </ul>
                    <ul>
                        <li (click)="getData()" style="cursor:pointer">All Products</li>
                    </ul>
                </div>
                <div class="men-position animated wow slideInUp" data-wow-delay=".5s">
                    <a href="single.html"><img src="assets/images/a5.jpg" alt=" " class="img-responsive" /></a>
                    <div class="men-position-pos">
                        <h5><span>55%</span> Flat Discount</h5>
                    </div>
                </div>
            </div>

            <div class="col-md-8 products-right">
                <br>
                <div style="float:right">
                    <pagination-controls (pageChange)="p=$event"></pagination-controls>
                </div>
                <!--
                <div style="float:right" [hidden]="visibleCategory">
                    <pagination-controls (pageChange)="p=$event"></pagination-controls>
                </div>
-->
                <br>
                <div align="center" class="col-md-12">
                    <div class="row">
                        <div class="col-md-2"></div>
                        <div class="col-md-8 col-sm-12" align="center">
                            <div class="input-group stylish-input-group">
                                <input type="text" class="form-control" placeholder="Let's find your product....." [(ngModel)]="search">
                                <span class="input-group-addon">
                        <button type="submit">
                            <span class="glyphicon glyphicon-search" (click)="searchFn()"></span>
                                </button>
                                </span>
                            </div>
                        </div>
                        <div class="col-md-2"></div>
                    </div>
                </div>
                <br><br>
                <br>

                <div class="products-right-grids-bottom">
                    <div class="row" myMatchHeight="panel" [hidden]="visible">
                        <div class="col-md-4 new-collections-grid" *ngFor="let data of productsList| filter:'name':search  |paginate: {itemsPerPage:9,currentPage: p}" style="text-align: center">
                            <div class="panel panel-block">
                                <div class="clearfix" ng-if="$index % 3 == 0"></div>


                                <div class="col-md-12 new-collections-grid1 animated wow slideInUp" data-wow-delay=".5s">
                                    <div class="new-collections-grid1-image" align="center">

                                        <a routerLink="/productdetails" class="product-image"><img class="panel-image" src="{{data.images[0].src}}" alt=" " style="text-align:center" height="175" width="150" /></a>
                                        <div class="new-collections-grid1-image-pos">
                                            <a (click)="product(data)">Quick View</a>
                                        </div>

                                    </div>
                                    <br>
                                </div>
                                <h4 class="panel-heading"><span (click)="product(data)">{{data.name}}</span></h4>
                                <div class="panel-body">
                                    <p> PRICE<span class="item_price"> {{data.regular_price}}</span></p>
                                    <br>
                                    <p><a class="item_add" style="border:1px solid red;color:red;padding:6px;">Add to cart </a></p>
                                </div>
                            </div>

                        </div>
                        <div class="clearfix"> </div>
                    </div>
                    <div class="row" myMatchHeight="panel" [hidden]="visibleCategory">
                        <div class="col-md-4 new-collections-grid" *ngFor="let data of categoryList| filter:'name':search  |paginate: {itemsPerPage:9,currentPage: p}" style="text-align: center">
                            <div class="panel panel-block">
                                <div class="clearfix" ng-if="$index % 3 == 0"></div>


                                <div class="col-md-12 new-collections-grid1 animated wow slideInUp" data-wow-delay=".5s">
                                    <div class="new-collections-grid1-image" align="center">

                                        <a routerLink="/productdetails" class="product-image"><img class="panel-image" src="{{data.images[0].src}}" alt=" " style="text-align:center" height="175" width="150" /></a>
                                        <div class="new-collections-grid1-image-pos">
                                            <a (click)="product(data)">Quick View</a>
                                        </div>

                                    </div>
                                    <br>
                                </div>
                                <h4 class="panel-heading"><span (click)="product(data)">{{data.name}}</span></h4>
                                <div class="panel-body">
                                    <p> PRICE<span class="item_price"> {{data.regular_price}}</span></p>
                                    <br>
                                    <p><a class="item_add" style="border:1px solid red;color:red;padding:6px;">Add to cart </a></p>
                                </div>
                            </div>

                        </div>
                        <div class="clearfix"> </div>
                    </div>
                    <a *ngIf="categoryList.length==0&&visible==true">No Results found</a>
                    <div class="clearfix"> </div>
                </div><br>
                <div style="float:right">
                    <pagination-controls (pageChange)="p=$event"></pagination-controls>
                </div>
                <!--
                <div style="float:right" [hidden]="visibleCategory">
                    <pagination-controls (pageChange)="p=$event"></pagination-controls>
                </div>
-->
            </div>
            <div class="clearfix"> </div>
        </div>
    </div>
    <!-- //breadcrumbs -->
</body>

如何在Angular4中实现多个分页?

3 个答案:

答案 0 :(得分:1)

您必须在每个分页项上添加ID

 <pagination-controls id="pagination1"....>  </pagination-controls>
 <pagination-controls id="pagination2"....>  </pagination-controls>

此外,您还必须为列表页面添加ID,如下所示:

<some-element *ngFor="let item of collection | paginate: { id: 'pagination1',
                                                      itemsPerPage: pageSize,
                                                      currentPage: p,
                                                      totalItems: total }">...</some-element>

答案 1 :(得分:0)

根据您的代码,首先需要解决javascript文件中出现的语法错误。要在angular4中实现分页,您需要使用以下代码:

<pagination-controls  id="some_id"
                  (pageChange)="pageChanged($event)"
                  maxSize="9"
                  directionLinks="true"
                  autoHide="true"
                  previousLabel="Previous"
                  nextLabel="Next"
                  screenReaderPaginationLabel="Pagination"
                  screenReaderPageLabel="page"
                  screenReaderCurrentLabel="You're on page">

根据要求,您可以选择ngx-pagination或ngx-pagination-bootstrap。 请浏览以下链接:

ngx-pagination - https://www.npmjs.com/package/ngx-pagination

ngx-pagination-bootstrap - https://www.npmjs.com/package/ngx-pagination-bootstrap

谢谢。

答案 2 :(得分:0)

您可以通过为分页控件提供id并将其传递给分页管道来实现

 paginate: { id: 'versionPagination' .........other param}


 <pagination-controls id="versionPagination">
    </pagination-controls>