typescript 材料表linke到Api

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 材料表linke到Api相关的知识,希望对你有一定的参考价值。

import { Observable } from 'rxjs/Rx';
import { MdPaginator } from '@angular/material';
import { DataSource } from '@angular/cdk/collections';
import { ApiHelperService } from './../../../_services/api-helper.service';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';

// INTERFACE
export interface Other {
    userId: number;
    id: number;
    title: string;
  }
  
// -------------------------------------
// DATABASE
// -------------------------------------

@Injectable()

export class otherDB {
    dataChange: BehaviorSubject<Other[]> = new BehaviorSubject<Other[]>([]);
    get data(): Other[] { return this.dataChange.value; }

// --- VARS
dataCount = 0;

  constructor (
    private api: ApiHelperService
  ) {}

  // --- TABLE CLEAR
  private clearTable(): void {
    this.data.splice(0);
    this.dataChange.next(this.data.slice());
  }

    // --- ADD DATA TO TABLE
    public addDataToTable(info: any): void {
        info.forEach(info => {
          const DATA: Other[] = this.data.slice();
          DATA.push({
            userId:info.userId,
            id: info.id,
            title: info.title
          });

          this.dataChange.next(DATA);

        });   
    }   
}

// -------------------------------------
// TABLE DATA SOURCE
// -------------------------------------

export class TableDataSource extends DataSource<any> {
    constructor(
      private otherDB: otherDB
    ) {
      super();
    }

    connect(): Observable<Other[]> {
        const displayDataChanges = [
          this.otherDB.dataChange,
        ];

        return Observable.merge(...displayDataChanges).map(() => {
            const data = this.otherDB.data.slice();
      
            return data.splice(0);
          });
        }
        disconnect() {}       


}
<h1>Hi from Other Component</h1>
<div class="example-container mat-elevation-z8">
    <md-progress-bar *ngIf="isLoadingData" mode="indeterminate" style="margin-bottom:20px;"></md-progress-bar>
    <md-table #table [dataSource]="dataSource">
      <!-- Name Column -->
      <ng-container mdColumnDef="userId">
        <md-header-cell *mdHeaderCellDef> Name </md-header-cell>
        <md-cell *mdCellDef="let element"> {{element.userId}} </md-cell>
      </ng-container>
  
      <!-- Height Column -->
      <ng-container mdColumnDef="id">
        <md-header-cell *mdHeaderCellDef> ID </md-header-cell>
        <md-cell *mdCellDef="let element"> {{element.id}} </md-cell>
      </ng-container>
  
      <!-- Skin Color Column -->
      <ng-container mdColumnDef="title">
        <md-header-cell *mdHeaderCellDef> Title </md-header-cell>
        <md-cell *mdCellDef="let element"> {{element.title}} </md-cell>
      </ng-container>

      <md-header-row *mdHeaderRowDef="displayedColumns"></md-header-row>
      <md-row *mdRowDef="let row; columns: displayedColumns;"></md-row>
    </md-table>
  </div>
  <!-- <div class="example-container mat-elevation-z8">
   -->
  <!-- </div> -->
h1{
    font-size: 2rem;
}
import {Component} from '@angular/core';
import { DataSource } from '@angular/cdk/collections';
import { otherDB, TableDataSource } from './other-db.component';
import { ApiHelperService } from './../../../_services/api-helper.service';

@Component  ({
    selector: 'sms-other',
    templateUrl: './other.component.html' ,
    styleUrls:['./other.component.scss'],
    providers: [otherDB]

})

export class OtherComponent {
    constructor(
        private otherDB: otherDB,
        private _api: ApiHelperService
      ) {}
      public isLoadingData = false;
      
      dataSource: TableDataSource | null;

    // --- COLUMNS DISPLAYED IN TABLE
    private displayedColumns: Array<string> = [
        'userId',
        'id',
        'title',
   
    ];

// --- GET SITES PAGE
private getSampleData(): void {
    this.isLoadingData = true;
    this._api.get('https://jsonplaceholder.typicode.com/posts')
    .subscribe(info => {
      console.log(info)
      const data = info.map(info => {
        return {
            userId:info.userId,
            id: info.id,
            title: info.title
       
        };
      });

      this.otherDB.addDataToTable(data);
      
            setTimeout( () => {
              this.isLoadingData = false;
            }, 1000)
        });
    }j

    ngOnInit() {
        this.dataSource = new TableDataSource(this.otherDB);
        this.getSampleData();
      }
          

}

以上是关于typescript 材料表linke到Api的主要内容,如果未能解决你的问题,请参考以下文章

在 Typescript 中将 React-Router Link 作为组件添加到 Material-UI?

typescript 字体 - 替换所有材料组件

typescript 材料的自定义日期适配器

材料表类型错误:无法添加属性表数据,对象不可扩展

将数据从 api 插入到材料选择输入角度

如何将角度材料表与后端数据动态绑定?