如何在角度2中实现加载更多按钮

时间:2017-06-26 12:27:20

标签: angular2-routing angular2-forms angular-template

我想在我的项目中添加更多加载按钮。我想在加载更多按钮上调用api并显示结果。如何实现这一点,在我的情况下,我一次得到200个结果,因为我已设置限制200,但我想在我的代码中加载更多按钮,以便我可以延迟加载。我想在按钮点击时调用api。

HTML

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <div class="margin-20">
            </div>
            <form [formGroup]="transactionForm"  (ngSubmit)="searchTransaction(transactionForm.value)" >

               <div class="form-group col-xs-2">
                    <label>Workshop</label>
                    <select class="form-control" [(ngModel)]="selectedWorkShop" formControlName="workshops">
                        <option value="" selected>--select--</option>                        
                        <option *ngFor="let workshop of workshops" value= {{workshop.id}}>{{workshop.name}}</option>
                    </select>
                    <small *ngIf="!transactionForm.controls.workshops.valid" class="text-danger">Required</small> 
                </div>
                 <div class="form-group col-xs-2">
                    <label>Start Date</label>
                    <input class="form-control" placeholder="Choose Date" [ngModel]="startDate"  formControlName="startDate" (focus)="toggleDatePicker1(true)"
                        readonly />
                    <date-picker *ngIf="showTimePicker1" [initDate]="startDate" (onDatePickerCancel)="toggleDatePicker1($event)" (onSelectDate)="setStartDate($event)"></date-picker>
                    <small *ngIf="!transactionForm.controls.startDate.valid" class="text-danger">Required</small>
                </div>
                 <div class="form-group col-xs-2">
                    <label>End Date</label>
                    <input class="form-control" placeholder="Choose Date" [ngModel]="endDate" formControlName="endDate" (focus)="toggleDatePicker2(true)"
                        readonly />
                    <date-picker *ngIf="showTimePicker2" [initDate]="endDate" (onDatePickerCancel)="toggleDatePicker2($event)" (onSelectDate)="setEndDate($event)"></date-picker>
                <small *ngIf="!transactionForm.controls.endDate.valid" class="text-danger">Required</small>
                </div>

                <!--<div class="form-group col-xs-2">
                    <label>From Date</label>
                    <input class="form-control" placeholder="Choose Date" [ngModel]="date" formControlName="date" (focus)="toggleDatePicker(true)"
                        readonly />
                    <date-picker *ngIf="showTimePicker" [initDate]="date" (onDatePickerCancel)="toggleDatePicker($event)" (onSelectDate)="setDate($event)"></date-picker>
                </div>--> 
                <div class="margin-20 col-xs-12">
                    <button type="submit" class="btn btn-primary" [disabled]="!transactionForm.valid">Search</button>&nbsp;&nbsp;&nbsp;
                    <img *ngIf="loading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=="
                    />
                </div>
            </form>
        </div>
    </div>
</div>
<br><br>
<div class="container">
    <div class="row">
        <div class="col-xs-12">
            <p *ngIf="isNoresult"><em>No Result Found</em></p>
            <table class='table table-hover' *ngIf="transactions">
                <thead>
                    <tr>
                        <th>User ID</th>
                        <th>Txn ID</th>
                        <th>Order Id</th>
                        <th>Mode</th>
                        <th>Transaction Type</th>
                        <th>Amount</th>
                        <th>Date</th>

                    </tr>
                </thead>
                <tbody>
                              <tr *ngFor="let transaction of transactions ">
                                <td>{{ transaction.user_id }}</td>
                                <td>{{ transaction.txn_id }}</td>
                                <td>{{ transaction.order_id }}</td>
                                <td>{{ transaction.mode  }}</td>
                                <td>{{ transaction.transaction_type }}</td>
                                <td>{{ transaction.amount | number : '1.2-2' }}</td>
                                <td>{{ transaction.date * 1000 | date:'dd-MM-yyyy' }}</td>

                            </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

组件

import { Component, OnInit } from '@angular/core';
import { FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import{DatePipe} from '@angular/common';
import { AlertService } from '../../../_services/index'
import { TransactionDetailsServices } from './transactionDetails.service';
// import { CustomerFilter, Customer } from '../models/index';



@Component({
    selector: 'transactionDetails',
    templateUrl: './transactionDetails.html'
})
export class TransactionDetails implements OnInit {
    public transactionForm :FormGroup;
    public workshops:any="";
    public selectedWorkShop="";
    public showTimePicker1:boolean;
    public showTimePicker2:boolean;
    public startDate=new Date();
    public endDate=new Date();
    public transactions:any;
    public loading:boolean;
    public isNoresult:boolean;
    public offset:number=0;
    constructor(
        private fb:FormBuilder,
        private alertService: AlertService,
        private transactionDetailsService: TransactionDetailsServices,
        private datePipe:DatePipe
    ) {
    }

    public phone: any;

    ngOnInit() {
        // const phoneRegex = `^[2-9]{2}[0-9]{8}$`;
        // this.searchCustomerForm = this.fb.group({
        //     phone: ['', [Validators.required, Validators.pattern(phoneRegex)]],
        //     phoneCC: [{value:'',disabled:true}]
        // });

        // this.orderForm = this.fb.group({
        //     categories: this.listCategory()
        // });
        this.transactionForm=this.fb.group({
            workshops:[this.listWorkshop(),Validators.required],
            startDate:['',Validators.required],
            endDate:['',Validators.required]
        })

    }
    listWorkshop() {
        this.weDoShoesCMSService.listWorkshop().subscribe(res => {
            this.workshops = res;
            this.selectedWorkShop="";
            console.log(res);
        },
            err => {
                this.alertService.error(err);
            });


    }
    toggleDatePicker1(status: boolean): void {
        this.showTimePicker1 = status;
    }
    toggleDatePicker2(status: boolean): void {
        this.showTimePicker2 = status;
    }
    setStartDate(date: any): void {
        this.startDate = date;
        console.log(this.startDate);
    }

    setEndDate(date: any): void {
        this.endDate = date;
        console.log(this.endDate);

    }

   searchTransaction(model:any){
    this.loading=true;   
    console.log(model);
    model.startDate=this.filterDate(model.startDate);
    model.endDate=this.filterDate(model.endDate);
    console.log(model.startDate);
    console.log(model.endDate);
    this.transactionDetailsService.searchTransaction(model).subscribe(res=>{
        this.transactions=res;
        if(res==null){
            this.isNoresult=true;
             this.loading=false;
        }
        else{
            this.isNoresult=false;
        console.log(res);
        this.loading=false;
        }
    },
       error=>{
          this.alertService.error(error);
           this.loading=false;
       });

    } 
   filterDate(date){
    return Date.parse(this.datePipe.transform(date, 'yyyy-MM-dd'))/1000;
   }
   convertDate(date){
       return Date.parse(this.datePipe.transform(date,''))
   }
}

服务

import {Component} from '@angular/core'
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Networks } from '../../networks/wedoshoes.networks';

@Injectable()
export class TransactionDetailsServices{
  constructor(private http:Http) {
    }

  searchTransaction(model:any){
      let requestUrl=this.generateUrl(model);
      let headers = this.httpHelper(true);
      let options = new RequestOptions({ headers: headers });
       return this.http.get(requestUrl, options)
            .map((response: Response) => response.json())
            .catch((error: any) => Observable.throw(error || JSON.parse(error._body)));

  }
  generateUrl(model:any):any{
     let requestUrl=Networks.OMS_BASE_URL+"/workshops/"+model.workshops+"/orders/payments?"+
     "start_date="+model.startDate+"&end_date="+model.endDate+"&offset=0&"+"limit=200";
     console.log(requestUrl);
     return requestUrl;
        }

  httpHelper(isSecure: boolean) {
        let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' });
        if (isSecure) {
            headers.append("Authorization", localStorage.getItem('token'));
            headers.append("X-UserID", localStorage.getItem('userId'));
        }
        return headers;
    }
}

1 个答案:

答案 0 :(得分:0)

    LoadMoreElement(){
          this.loadResult=true;
          console.log(this.loadResult);
          this.calculateOffset();
          this.findMoreTransaction(this.formOutput);

       }

calculateOffset(){
    this.offset=this.offset+this.limit;
}


        findMoreTransaction(model:any){
            this.transactionDetailsService.searchTransaction(model,this.offset,this.limit).subscribe(res=>{
                console.log(res);
                if(res==null){
                    this.alertService.success("No Record Found");
                     this.loading=false;
                     this.loadResult=false;
                }
                else{
                    if(this.transactions==null){
                         this.transactions=[];
                         this.loading=false;
                    }
                    else{
                        this.loadResult=false;
                    }
                this.transactions=this.transactions.concat(res);
               // this.fillTransaction();
                console.log(this.transactions);

                }
            },
               error=>{
                  this.alertService.error(error);
                   this.loading=false;
               });
        }
        }