从Angular4 Service获取数据到Material Design表

时间:2017-09-27 15:12:03

标签: angular material-design

我正在尝试使用Angular4服务将数据提取到Material Design表中。我已经看到很多很多例子在组件中使用数组,但是找不到从服务中提取数据的简单示例。我做了几次尝试,不知道下一步该去哪里。我的代码如下,并提前感谢您的帮助!

组件:

import { Component, OnInit } from '@angular/core';
import { OverUnderService } from './over-under.service';
import { Over } from './over-under.interface';
import { MdTableModule } from '@angular/material';
import { DataSource } from '@angular/cdk/table';
import { MdSort } from '@angular/material';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { Http, Response, RequestOptions, Headers, Request, RequestMethod } from '@angular/http';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';


@Component({
  selector: 'app-over-under',
  templateUrl: './over-under.component.html',
  styleUrls: ['./over-under.component.css']
})

export class OverUnderComponent implements OnInit {
  data: Array<any>;
  displayedColumns = ['homeTeam', 'vegasLine', 'roadTeam', 'over'];
  dataSource: Over;

  constructor(private _http: OverUnderService) {
  }

  ngOnInit() {
    this._http.getOverUnder().subscribe(res => this.data = res);
  }

}

服务:

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

@Injectable()
export class OverUnderService {

  constructor(private http: Http) { }

  getOverUnder() {
    return this.http.get('assets/over_under.json')
        .map(res => res .json());
  }
}

HTML:

<md-table #table [dataSource]="dataSource">
    <ng-container cdkColumnDef="homeTeam">
        <md-header-cell cdkHeaderCellDef>Home Team</md-header-cell>
        <md-cell cdkCellDef="let data"> <b>{{ data.homeTeam }}.</b>
        </md-cell>
    </ng-container>

    <ng-container cdkColumnDef="vegasLine">
        <md-header-cell cdkHeaderCellDef>Vegas</md-header-cell>
        <md-cell cdkCellDef="let data"> <b>{{ data.vegasLine }}.</b>
        </md-cell>
    </ng-container>

    <ng-container cdkColumnDef="roadTeam">
        <md-header-cell cdkHeaderCellDef>Road Team</md-header-cell>
        <md-cell cdkCellDef="let data"> <b>{{ data.roadTeam }}.</b>
        </md-cell>
    </ng-container>

    <ng-container cdkColumnDef="over">
        <md-header-cell cdkHeaderCellDef>O/U</md-header-cell>
        <md-cell cdkCellDef="let data"> <b>{{ data.over.under }}.</b>
        </md-cell>
    </ng-container>

    <md-header-row cdkHeaderRowDef="displayedColumns"></md-header-row>
    <md-row *cdkRowDef="let data; columns: displayedColumns;"></md-row>
</md-table>

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing/app-routing.module';
import { AppComponent } from './app.component';
import { MdTableModule } from '@angular/material';
import { CdkTableModule } from '@angular/cdk/table';

// import { AgGridModule } from 'ag-grid-angular/main';
import { OverUnderService } from './over-under/over-under.service';
import { OverUnderComponent } from './over-under/over-under.component';
import { DvoaComponent } from './dvoa/dvoa.component';

@NgModule({
  declarations: [
    AppComponent,
    OverUnderComponent,
    DvoaComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRoutingModule,
    MdTableModule,
    CdkTableModule
    // AgGridModule.withComponents([])
  ],
  providers: [OverUnderService],
  bootstrap: [AppComponent]
})
export class AppModule { }

1 个答案:

答案 0 :(得分:0)

在查看了所有以这种方式实现的教程之后,我遇到了相同的确切问题:我将所有代码供您理解:

  

service-http.service.ts

  在这里,我正在进行http调用,以获取有关yahoo的财务信息,并使它成为将其注入到我需要的位置的服务。我在管道内进行映射,以确保返回所需的数组。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable} from 'rxjs';
import { TableItem } from '../../models/tableItem.model';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ServiceHttpService {
  private data: TableItem[] = [];
  constructor(private http: HttpClient) { }

  private configUrl = 'http://query2.finance.yahoo.com/v7/finance/options/aapl';

  getPrice(): Observable<TableItem[]> {
    return this.http.get<TableItem[]>(this.configUrl).pipe(map(res => {
        return <TableItem[]>res['optionChain'].result[0].options[0].calls;
    }));
  }
}
  

table.component.ts

这是我在构造函数中调用服务的部分,当我获得Observable(.subscribe)的响应时,将使用数据实例化表。

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatSort } from '@angular/material';
import { TableDataSource } from './table-datasource';
import { ServiceHttpService } from '../../services/http-service/service-http.service';
@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  dataSource: TableDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  columns = [
    { columnDef: 'ask', header: 'Ask'},
    { columnDef: 'bid', header: 'Bid'},
    { columnDef: 'change', header: 'Change'},
    { columnDef: 'contractSize', header: 'Contract Size'},
    { columnDef: 'contractSymbol', header: 'Contract Symbol'},
    { columnDef: 'currency', header: 'Currency'},
    { columnDef: 'expiration', header: 'Expiration'},
    { columnDef: 'impliedVolatility', header: 'Implied Volatility'},
    { columnDef: 'inTheMoney', header: 'In The Money'},
    { columnDef: 'lastPrice', header: 'LastPrice'},
    { columnDef: 'lastTradeDate', header: 'Last Trade Date'},
    { columnDef: 'openInterest', header: 'Open Interest'},
    { columnDef: 'percentChange', header: 'Percent Change'},
    { columnDef: 'strike', header: 'Strike'},
    { columnDef: 'volume', header: 'Volume'},
  ];
  displayedColumns = this.columns.map(c => c.columnDef);
  constructor( private serviceHttpService: ServiceHttpService) {
    this.serviceHttpService.getPrice().subscribe(data => {
      this.dataSource = new TableDataSource(data, this.paginator, this.sort);
    });
  }
  ngOnInit() {}
}
  

table-datasource.ts

这是数据源的代码,仅供您查看,在构造函数中,我传递了table.component.ts中获得的数据。 / p>

import { DataSource } from '@angular/cdk/collections';
import { MatPaginator, MatSort } from '@angular/material';
import { map } from 'rxjs/operators';
import { Observable, of as observableOf, merge } from 'rxjs';
import { TableItem } from '../../models/tableItem.model';

/**
 * Data source for the Table view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class TableDataSource extends DataSource<TableItem> {
  constructor(private data: TableItem[], private paginator: MatPaginator, private sort: MatSort) {
    super();
  }

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<TableItem[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    // Set the paginators length
    this.paginator.length = this.data.length;

    return merge(...dataMutations).pipe(map(() => {
      return this.getPagedData(this.getSortedData([...this.data]));
    }));
  }

  /**
   *  Called when the table is being destroyed. Use this function, to clean up
   * any open connections or free any held resources that were set up during connect.
   */
  disconnect() {}

  /**
   * Paginate the data (client-side). If you're using server-side pagination,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getPagedData(data: TableItem[]) {
    const startIndex = this.paginator.pageIndex * this.paginator.pageSize;
    return data.splice(startIndex, this.paginator.pageSize);
  }

  /**
   * Sort the data (client-side). If you're using server-side sorting,
   * this would be replaced by requesting the appropriate data from the server.
   */
  private getSortedData(data: TableItem[]) {
    if (!this.sort.active || this.sort.direction === '') {
      return data;
    }

    return data.sort((a, b) => {
      const isAsc = this.sort.direction === 'asc';
      switch (this.sort.active) {
        case 'ask': return compare(a.ask, b.ask, isAsc);
        case 'bid': return compare(a.bid, b.bid, isAsc);
        case 'change': return compare(a.change, b.change, isAsc);
        case 'contractSize': return compare(a.contractSize, b.contractSize, isAsc);
        case 'contractSymbol': return compare(a.contractSymbol, b.contractSymbol, isAsc);
        case 'currency': return compare(a.currency, b.currency, isAsc);
        case 'expiration': return compare(a.expiration, b.expiration, isAsc);
        case 'impliedVolatility': return compare(a.impliedVolatility, b.impliedVolatility, isAsc);
        case 'inTheMoney': return compare(a.inTheMoney, b.inTheMoney, isAsc);
        case 'lastPrice': return compare(a.lastPrice, b.lastPrice, isAsc);
        case 'lastTradeDate': return compare(a.lastTradeDate, b.lastTradeDate, isAsc);
        case 'openInterest': return compare(a.openInterest, b.openInterest, isAsc);
        case 'percentChange': return compare(a.percentChange, b.percentChange, isAsc);
        case 'strike': return compare(a.strike, b.strike, isAsc);
        case 'volume': return compare(a.volume, b.volume, isAsc);
        default: return 0;
      }
    });
  }
}

/** Simple sort comparator for example ID/Name columns (for client-side sorting). */
function compare(a, b, isAsc) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
  

tableItem.model.ts

这是信息的模型,以确保它们尊重这种类型(当我获取数据时,我希望它成为这种类型)

export interface TableItem {
  ask: number;
  bid: number;
  change: number;
  contractSize: string;
  contractSymbol: string;
  currency: string;
  expiration: number;
  impliedVolatility: number;
  inTheMoney: boolean;
  lastPrice: number;
  lastTradeDate: number;
  openInterest: number;
  percentChange: number;
  strike: number;
  volume: number;
}
  

table.component.html

这只是组件html,您可以通过table.component.ts中的columns属性查看动态创建行的方式。

<div class="mat-elevation-z8">
  <table mat-table #table [dataSource]="dataSource" matSort aria-label="Elements">
    <!-- Id Column -->
    <ng-container *ngFor="let item of columns" [matColumnDef]="item.columnDef" >
      <th mat-header-cell *matHeaderCellDef mat-sort-header>{{item.header}}</th>
      <td mat-cell *matCellDef="let row">{{row[item.columnDef]}}</td>
    </ng-container>


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

  <mat-paginator #paginator
    [length]="columns.length"
    [pageIndex]="0"
    [pageSize]="50"
    [pageSizeOptions]="[25, 50, 100, 250]">
  </mat-paginator>
</div>

如果您需要任何其他信息或更多详细信息,我们将很乐意为您提供

最佳