Http和DataSource的材料2分页

时间:2017-10-22 22:05:38

标签: angular rest pagination angular-material2 angular-cdk

我在使用DataSource进行Material Pagination时遇到了问题。我需要从服务中获取REST服务提供的整理项目(我无法对其进行更改)。到目前为止,我能做到的唯一方法是两次做同样的请求,这是不对的。

如果你看一下" servers-collection.component.ts"我称之为" getServiceData"只是为了获得分页的总项目(" total_items"在请求响应中)。我正在寻找的是直接从主要请求中获取数据。

这是我的原始回复(GET):

{
    "_links": {
        "self": {
            "href": "https://{URL}/servers?page=1"
        },
        "first": {
            "href": "http://{URL}/servers"
        },
        "last": {
            "href": "http://{URL}/servers?page=100"
        },
        "next": {
            "href": "http://{URL}/servers?page=2"
        }
    },
    "_embedded": {
        "servers": [
            {
                "id": 1,
                "name": "Server Name",
                "ipAddress": "111.222.333.444",
                "hostName": "server.hostname.com",
                "_links": {
                    "self": {
                        "href": "http://{URL}/servers/1"
                    }
                }
            }
        ]
    },
    "page_count": 100,
    "page_size": 5,
    "total_items": 498,
    "page": 1
}

......这就是我采取的措施:

服务器-collection.component.html

<div class="example-container mat-elevation-z8">
    <mat-table #table [dataSource]="dataSource">
        <!-- ID Column -->
        <ng-container matColumnDef="id">
            <mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
            <mat-cell *matCellDef="let row"> {{row.id}} </mat-cell>
        </ng-container>

        <!-- Name Column -->
        <ng-container matColumnDef="name">
            <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
            <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
        </ng-container>

        <!-- IP Address Column -->
        <ng-container matColumnDef="ipAddress">
            <mat-header-cell *matHeaderCellDef> IP Address </mat-header-cell>
            <mat-cell *matCellDef="let row"> {{row.ipAddress}} </mat-cell>
        </ng-container>

        <!-- Host Name Column -->
        <ng-container matColumnDef="hostName">
            <mat-header-cell *matHeaderCellDef> Hostname </mat-header-cell>
            <mat-cell *matCellDef="let row"> {{row.hostName}} </mat-cell>
        </ng-container>

        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>

    <mat-paginator #pagination
                   [length]="length"
                   [pageSize]="pageSize"
                   [pageSizeOptions]="pageSizeOptions"
                   (page)="pageEvent = loadData($event)">
    </mat-paginator>
</div>

服务器-collection.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, PageEvent } from "@angular/material";

import { ServersService } from "../../../shared/services/servers/servers.service";
import { ServersDataSource } from "../../../shared/data-source/server.datasource";

@Component({
  selector: 'app-servers-collection',
  templateUrl: './servers-collection.component.html',
  styleUrls: ['./servers-collection.component.css']
})
export class ServersCollectionComponent implements OnInit {
    // Display Data
    displayedColumns = ['id', 'name', 'ipAddress', 'hostName'];
    dataSource:ServersDataSource|null;
    pageEvent:PageEvent;

    //Pagination
    length:number;
    pageSize:number = 10;
    pageIndex:number = 1;
    pageSizeOptions:number[] = [5, 10, 25, 50, 100];

    @ViewChild(MatPaginator) pagination: MatPaginator;

    constructor(public serversService:ServersService) {
    }

    ngOnInit() {
        this.loadData();
    }

    loadData() {
        this.serversService.getServiceData(this.pageIndex, this.pageSize).subscribe(serviceData => {
                this.length = serviceData['total_items'];
            }
        );

        this.dataSource = new ServersDataSource(this.serversService, this.pagination);
    }
}

server.datasource.ts

import { DataSource } from '@angular/cdk/collections';
import { Observable } from 'rxjs/Observable';
import { MatPaginator } from "@angular/material";

import { Server } from "../interfaces/Server";
import { ServersService } from "../services/servers/servers.service";

export class ServersDataSource extends DataSource<any> {
    constructor(private _serverService: ServersService, private _pagination : MatPaginator) {
        super();
    }

    connect(): Observable<Server[]> {
        return this._serverService.getServers(this._pagination.pageIndex + 1, this._pagination.pageSize);
    }

    disconnect() {}
}

servers.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from "rxjs/Observable";
import { Server } from "../../interfaces/Server";
import 'rxjs/add/operator/map';

@Injectable()
export class ServersService {
    url:string = 'http://{URL}/servers';
    servers:Server[];

    constructor(private http: Http) {
    }

    getServiceData(startIndex, pageSize) {
        return this.http.get(this.url + '?page=' + startIndex + '&limit=' + pageSize)
            .map(response => response.json());
    }

    getServers(startIndex, pageSize): Observable<Server[]> {
        return this.http.get(this.url + '?page=' + startIndex + '&limit=' + pageSize)
            .map(this.extractData);
    }

    extractData(result: Response): Server[] {
        return result.json()['_embedded']['servers'];
    }
}

提前谢谢大家!

2 个答案:

答案 0 :(得分:9)

自己找到答案。事实证明这是范围(我没有正确理解)。

我不能直接在Observer里面设置一个变量给类。我能做的就是调用一个方法并传递我需要的东西。可能看起来很基本但是花了我一个星期才来到这里。

所以这就是编码最终的结果:

服务器-collection.component.ts:

import { Component, OnInit } from '@angular/core';
import { ServersService } from "../../../shared/services/servers/servers.service";
import { ServersDataSource } from "../../../shared/data-source/server.datasource";

@Component({
    selector: 'app-servers-collection',
    templateUrl: './servers-collection.component.html',
    styleUrls: ['./servers-collection.component.css']
})
export class ServersCollectionComponent implements OnInit {
    // Data
    displayedColumns = ['id', 'name', 'ipAddress', 'hostName'];
    dataSource:ServersDataSource|null;
    data:any;

    // Pagination
    length:number;
    pageIndex:number = 1;
    pageSize:number = 10;
    pageSizeOptions:number[] = [5, 10, 25, 50, 100];

    constructor(private _serversService:ServersService) {
    }

    ngOnInit() {
        this.loadData();
    }

    loadData() {
        this.data = this._serversService.getData(this.pageIndex, this.pageSize);
        this.data.subscribe(data => {
            this.setPagination(data['total_items'], data['page'], data['page_size']);
            this.dataSource = new ServersDataSource(data['_embedded']['servers']);
        });
    }

    setPagination(length, startIndex, pageSize) {
        this.length = length;
        this.pageIndex = startIndex;
        this.pageSize = pageSize;
    }

    onPaginateChange(event) {
        this.pageIndex = event.pageIndex;
        this.pageSize = event.pageSize;
        this.loadData();
    }
}

server.datasource.ts:

import { DataSource } from '@angular/cdk/collections';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { Server } from "../interfaces/Server";

export class ServersDataSource extends DataSource<any> {
    constructor(private _servers:Server[]) {
        super();
    }

    connect(): Observable<Server[]> {
        return Observable.of(this._servers);
    }

    disconnect() {}
}

servers.service.ts:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';

@Injectable()
export class ServersService {
    url:string = 'http://{URL}/servers';

    constructor(private http: Http) {
    }

    getData(startIndex, pageSize): Observable<any> {
        return this.http.get(this.url + '?page=' + startIndex + '&limit=' + pageSize)
            .map(this.extractData);
    }

    extractData(result: Response) {
        return result.json();
    }
}

希望这有助于某人。

答案 1 :(得分:1)

非常感谢这段代码。我用过这样的分页器:

<mat-paginator #pagination [length]="length" 
[pageSize]="pageSize 
[pageSizeOptions]="pageSizeOptions" 
(page)="pageEvent = onPaginationChange($event)"> 
// instead of loadData($event) 
</mat-paginator>

我也对此进行了修改,因为第一页的索引为0,数据上的索引为1

 onPaginateChange(event) {
    this.pageIndex = event.pageIndex + 1;
    this.pageSize = event.pageSize;
    this.loadData();
}