本文介绍了如何将从服务接收到的 json 数据传递到 angular 4 的角度材料中的组件中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 4 和角度材料的新手,我正在尝试将带有 http、分页、排序和过滤的角度材料数据表添加到我的仪表板组件中,使用硬编码数组,我能够实现过滤、排序和分页.但我无法将服务中的 json 数据传递到数组中.

任何帮助将不胜感激.提前致谢..!!!

请在下面找到我的代码.

test.json

[{"名字": "吉尔","LastName": "史密斯",分数":取消资格"}, {"名字": "夏娃","LastName": "杰克逊",分数":94"}, {"FirstName": "约翰","LastName": "母鹿",分数":80"}, {"名字": "亚当","LastName": "约翰逊",得分":67"}]

component.service

import { Injectable } from '@angular/core';从'@angular/common/http' 导入 { HttpClient };导入 { HttpModule, Http, Response, Headers, RequestOptions } from'@角度/http';从 'rxjs/Observable' 导入 { Observable };导入 'rxjs/add/operator/map';导入 'rxjs/add/operator/catch';从'../models/fleetData.model'导入{用户};@Injectable()导出类 FleetDataService {private serviceUrl = '../../assets/data/test.json';构造函数(私有http:HttpClient){}getFleetData(): Observable{返回 this.http.get(this.serviceUrl);}}

component.ts

import { Component, AfterViewInit, ViewChild } from '@angular/core';从'../../services/fleet-data.service'导入{ FleetDataService};从 '../../services/loader.service' 导入 { LoaderService };从 'rxjs/Observable' 导入 { Observable };导入 'rxjs/add/observable/of';从@angular/cdk/collections"导入{DataSource};从'../../models/fleetData.model'导入{用户};从@angular/material"导入{MatPaginator、MatTableDataSource、MatSort};从 'rxjs/BehaviorSubject' 导入 {BehaviorSubject};@成分({选择器:应用仪表板",templateUrl: './dashboard.component.html',styleUrls: ['./dashboard.component.scss']})导出类 DashboardComponent 实现 AfterViewInit {//dataSource = new UserDataSource(this.getFleetData);displayColumns = ['First Name', 'Last Name', 'Score'];dataSource = new MatTableDataSource(ELEMENT_DATA);@ViewChild(MatPaginator) 分页器:MatPaginator;@ViewChild(MatSort) 排序:MatSort;应用过滤器(过滤器值:字符串){filterValue = filterValue.trim();//去除空格filterValue = filterValue.toLowerCase();//MatTableDataSource 默认值小写匹配this.dataSource.filter = filterValue;}构造函数(私有 getFleetData:FleetDataService,私有 loaderService:加载服务) { }ngAfterViewInit() {this.dataSource.paginator = this.paginator;this.dataSource.sort = this.sort;}}const ELEMENT_DATA: 用户 [] =[{"名字": "吉尔","LastName": "史密斯",分数":取消资格"}, {"名字": "夏娃","LastName": "杰克逊",分数":94"}, {"FirstName": "约翰","LastName": "母鹿",分数":80"}, {"名字": "亚当","LastName": "约翰逊",得分":67"},{"名字": "吉尔","LastName": "史密斯",分数":取消资格"}, {"名字": "夏娃","LastName": "杰克逊",分数":94"}, {"FirstName": "约翰","LastName": "母鹿",分数":80"}, {"名字": "亚当","LastName": "约翰逊",得分":67"},{"名字": "吉尔","LastName": "史密斯",分数":取消资格"}, {"名字": "夏娃","LastName": "杰克逊",分数":94"}, {"FirstName": "约翰","LastName": "母鹿",分数":80"}, {"名字": "亚当","LastName": "约翰逊",得分":67"},{"名字": "吉尔","LastName": "史密斯",分数":取消资格"}, {"名字": "夏娃","LastName": "杰克逊",分数":94"}, {"FirstName": "约翰","LastName": "母鹿",分数":80"}, {"名字": "亚当","LastName": "约翰逊",得分":67"}]导出类 UserDataSource 扩展了 DataSource{构造函数(私有 getFleetData:FleetDataService){极好的();}connect(): Observable{返回 this.getFleetData.getFleetData();}断开连接(){}}

component.html

Hi Dashboard

<div class="example-header"><mat-form-field><input matInput (keyup)="applyFilter($event.target.value)"占位符=过滤器"></mat-form-field>

<div class="example-container mat-elevation-z8"><mat-table [dataSource]="dataSource" matSort><!-- 名字列--><ng-container matColumnDef="名字"><mat-h​​eader-cell *matHeaderCellDef mat-sort-header>名字 </mat-标题单元格><mat-cell *matCellDef="let user">{{user.FirstName}} </mat-cell></ng-容器><!-- 姓氏列--><ng-container matColumnDef="Last Name"><mat-h​​eader-cell *matHeaderCellDef mat-sort-header>姓氏 </mat-标题单元格><mat-cell *matCellDef="let user">{{user.LastName}} </ng-容器><!-- 分数列--><ng-container matColumnDef="Score"><mat-h​​eader-cell *matHeaderCellDef mat-sort-header>得分 </mat-h​​eader-单元格><mat-cell *matCellDef="let user">{{user.Score}} </mat-cell></ng-容器><mat-h​​eader-row *matHeaderRowDef="displayedColumns"></mat-h​​eader-row><mat-row *matRowDef="让行;列:displayColumns;"></mat-row></mat-table><mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>

解决方案

我猜您对在表中加载数据的两种不同方式感到困惑.从您的 component.service,特别是FleetDataService"类的外观来看,您正在尝试获得 Observable 响应.对于 component.ts,正确的方法可能如下所示:

import { Component, AfterViewInit, ViewChild } from '@angular/core';从'../../services/fleet-data.service'导入{ FleetDataService};从 '../../services/loader.service' 导入 { LoaderService };从 'rxjs/Observable' 导入 { Observable };导入 'rxjs/add/observable/of';从@angular/cdk/collections"导入{DataSource};从'../../models/fleetData.model'导入{用户};从@angular/material"导入{MatPaginator、MatTableDataSource、MatSort};从 'rxjs/BehaviorSubject' 导入 {BehaviorSubject};@成分({选择器:应用仪表板",templateUrl: './dashboard.component.html',styleUrls: ['./dashboard.component.scss']})导出类 DashboardComponent 实现 AfterViewInit {车队数据 = 空;dataSource = new MatTableDataSource(this.fleetData);displayColumns = ['First Name', 'Last Name', 'Score'];@ViewChild(MatPaginator) 分页器:MatPaginator;@ViewChild(MatSort) 排序:MatSort;应用过滤器(过滤器值:字符串){filterValue = filterValue.trim();//去除空格filterValue = filterValue.toLowerCase();//MatTableDataSource 默认值小写匹配this.dataSource.filter = filterValue;}构造函数(私有 getFleetData:FleetDataService,私有 loaderService:加载服务) {getFleetData.getFleetData().subscribe(数据 =>{this.fleetData = 数据;this.dataSource.data = this.fleetData;});}ngAfterViewInit() {this.dataSource.paginator = this.paginator;this.dataSource.sort = this.sort;}}

与上面的例子类似,你所尝试的,可以用另一种方式来完成,如下图:

import { Component, AfterViewInit, ViewChild } from '@angular/core';从'../../services/fleet-data.service'导入{ FleetDataService};从 '../../services/loader.service' 导入 { LoaderService };从 'rxjs/Observable' 导入 { Observable };导入 'rxjs/add/observable/of';从@angular/cdk/collections"导入{DataSource};从'../../models/fleetData.model'导入{用户};从@angular/material"导入{MatPaginator、MatTableDataSource、MatSort};从 'rxjs/BehaviorSubject' 导入 {BehaviorSubject};@成分({选择器:应用仪表板",templateUrl: './dashboard.component.html',styleUrls: ['./dashboard.component.scss']})导出类 DashboardComponent 实现 AfterViewInit {displayColumns = ['First Name', 'Last Name', 'Score'];dataSource = new MatTableDataSource(ELEMENT_DATA);@ViewChild(MatPaginator) 分页器:MatPaginator;@ViewChild(MatSort) 排序:MatSort;应用过滤器(过滤器值:字符串){filterValue = filterValue.trim();//去除空格filterValue = filterValue.toLowerCase();//MatTableDataSource 默认值小写匹配this.dataSource.filter = filterValue;}构造函数(私有 getFleetData:FleetDataService,私有 loaderService:加载服务) { }ngAfterViewInit() {this.dataSource.paginator = this.paginator;this.dataSource.sort = this.sort;}}const ELEMENT_DATA: 用户 [] =[{"名字": "吉尔","LastName": "史密斯",分数":取消资格"}, {"名字": "夏娃","LastName": "杰克逊",分数":94"}, {"FirstName": "约翰","LastName": "母鹿",分数":80"}, {"名字": "亚当","LastName": "约翰逊",得分":67"},{"名字": "吉尔","LastName": "史密斯",分数":取消资格"}, {"名字": "夏娃","LastName": "杰克逊",分数":94"}, {"FirstName": "约翰","LastName": "母鹿",分数":80"}, {"名字": "亚当","LastName": "约翰逊",得分":67"},{"名字": "吉尔","LastName": "史密斯",分数":取消资格"}, {"名字": "夏娃","LastName": "杰克逊",分数":94"}, {"FirstName": "约翰","LastName": "母鹿",分数":80"}, {"名字": ""亚当","LastName": "约翰逊",得分":67"},{"名字": "吉尔","LastName": "史密斯",分数":取消资格"}, {"名字": "夏娃","LastName": "杰克逊",分数":94"}, {"FirstName": "约翰","LastName": "母鹿",分数":80"}, {"名字": "亚当","LastName": "约翰逊",得分":67"}];

我还看到您的代码中有很多问题.我希望你没有错过任何关于 MatPaginator 和 MatSort 的内容.

I am new to Angular 4 and angular material and i am trying to add the angular material data table with http, pagination, sorting and filtering into my dashboard component, With hard-coded array i was able to achieve filter, sort and pagination. But i am not able to pass a json data from service into the array.

Any help would be appreciated.Thanks in advance..!!!

Please find my code below.

test.json

[{
 "FirstName": "Jill",
 "LastName": "Smith",
 "Score": "disqualified"
}, {
 "FirstName": "Eve",
 "LastName": "Jackson",
 "Score": "94"
}, {
 "FirstName": "John",
 "LastName": "Doe",
 "Score": "80"
}, {
 "FirstName": "Adam",
 "LastName": "Johnson",
 "Score": "67"
}]

component.service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpModule, Http, Response, Headers, RequestOptions } from 
'@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { User } from '../models/fleetData.model';

@Injectable()
export class FleetDataService {
 private serviceUrl = '../../assets/data/test.json';
  constructor(private http: HttpClient) { }
    getFleetData(): Observable<User[]> {
  return this.http.get<User[]>(this.serviceUrl);
 }

}

component.ts

import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { FleetDataService } from '../../services/fleet-data.service';
import { LoaderService } from '../../services/loader.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import {DataSource} from '@angular/cdk/collections';
import { User } from '../../models/fleetData.model';
import {MatPaginator, MatTableDataSource, MatSort} from '@angular/material';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
@Component({
   selector: 'app-dashboard',
   templateUrl: './dashboard.component.html',
   styleUrls: ['./dashboard.component.scss']
})

export class DashboardComponent implements AfterViewInit {
  // dataSource = new UserDataSource(this.getFleetData);
  displayedColumns = ['First Name', 'Last Name', 'Score'];
  dataSource = new MatTableDataSource<User>(ELEMENT_DATA);
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults 
    to lowercase matches
    this.dataSource.filter = filterValue;
  }
  constructor(private getFleetData: FleetDataService, private loaderService: 
   LoaderService) { }
   ngAfterViewInit() {
     this.dataSource.paginator = this.paginator;
     this.dataSource.sort = this.sort;
    }
  }
  const ELEMENT_DATA: User[] = 
  [{
    "FirstName": "Jill",
    "LastName": "Smith",
    "Score": "disqualified"
   }, {
    "FirstName": "Eve",
    "LastName": "Jackson",
    "Score": "94"
   }, {
    "FirstName": "John",
    "LastName": "Doe",
    "Score": "80"
   }, {
    "FirstName": "Adam",
    "LastName": "Johnson",
    "Score": "67"
   },{
     "FirstName": "Jill",
     "LastName": "Smith",
     "Score": "disqualified"
    }, {
     "FirstName": "Eve",
     "LastName": "Jackson",
     "Score": "94"
    }, {
     "FirstName": "John",
     "LastName": "Doe",
     "Score": "80"
    }, {
    "FirstName": "Adam",
    "LastName": "Johnson",
    "Score": "67"
   },{
    "FirstName": "Jill",
    "LastName": "Smith",
    "Score": "disqualified"
   }, {
    "FirstName": "Eve",
    "LastName": "Jackson",
    "Score": "94"
   }, {
    "FirstName": "John",
    "LastName": "Doe",
    "Score": "80"
   }, {
    "FirstName": "Adam",
    "LastName": "Johnson",
    "Score": "67"
   },{
    "FirstName": "Jill",
    "LastName": "Smith",
    "Score": "disqualified"
   }, {
    "FirstName": "Eve",
    "LastName": "Jackson",
    "Score": "94"
   }, {
    "FirstName": "John",
    "LastName": "Doe",
    "Score": "80"
   }, {
    "FirstName": "Adam",
    "LastName": "Johnson",
    "Score": "67"
   }]
   export class UserDataSource extends DataSource<any> {
    constructor(private getFleetData: FleetDataService) {
    super();
   }
    connect(): Observable<User[]> {
     return this.getFleetData.getFleetData();
   }
    disconnect() {}
  }

component.html

<h1>Hi Dashboard</h1>
<div class="example-header">
  <mat-form-field>
    <input matInput (keyup)="applyFilter($event.target.value)" 
    placeholder="Filter">
  </mat-form-field>
</div>
<div class="example-container mat-elevation-z8">
  <mat-table [dataSource]="dataSource" matSort>
    <!-- First Name Column -->
  <ng-container matColumnDef="First Name">
    <mat-header-cell *matHeaderCellDef mat-sort-header> First Name </mat-
      header-cell>
    <mat-cell *matCellDef="let user"> {{user.FirstName}} </mat-cell>
  </ng-container>
    <!-- Last Name Column -->
  <ng-container matColumnDef="Last Name">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Last Name </mat-
      header-cell>
    <mat-cell *matCellDef="let user"> {{user.LastName}} </mat-cell>
  </ng-container>
   <!-- Score Column -->
  <ng-container matColumnDef="Score">
    <mat-header-cell *matHeaderCellDef mat-sort-header> Score </mat-header-
      cell>
    <mat-cell *matCellDef="let user"> {{user.Score}} </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 [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</div>
解决方案

I guess you are confused with two different ways to load data in the table. From the looks of your component.service, specifically 'FleetDataService' class, you are trying to get and Observable response. The correct way could be as below, for component.ts:

import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { FleetDataService } from '../../services/fleet-data.service';
import { LoaderService } from '../../services/loader.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import {DataSource} from '@angular/cdk/collections';
import { User } from '../../models/fleetData.model';
import {MatPaginator, MatTableDataSource, MatSort} from '@angular/material';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
@Component({
   selector: 'app-dashboard',
   templateUrl: './dashboard.component.html',
   styleUrls: ['./dashboard.component.scss']
})

export class DashboardComponent implements AfterViewInit {
  fleetData = null;
  dataSource = new MatTableDataSource(this.fleetData);
  displayedColumns = ['First Name', 'Last Name', 'Score'];

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults 
    to lowercase matches
    this.dataSource.filter = filterValue;
  }
  constructor(private getFleetData: FleetDataService, private loaderService: 
   LoaderService) { 
   getFleetData.getFleetData().subscribe(
   data => {
    this.fleetData = data;
    this.dataSource.data = this.fleetData;  
   });
   }
   ngAfterViewInit() {
     this.dataSource.paginator = this.paginator;
     this.dataSource.sort = this.sort;
    }
  }

Similarly in the above example, what you are trying , can be done in another way, as shown below:

import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { FleetDataService } from '../../services/fleet-data.service';
import { LoaderService } from '../../services/loader.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import {DataSource} from '@angular/cdk/collections';
import { User } from '../../models/fleetData.model';
import {MatPaginator, MatTableDataSource, MatSort} from '@angular/material';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
@Component({
   selector: 'app-dashboard',
   templateUrl: './dashboard.component.html',
   styleUrls: ['./dashboard.component.scss']
})

export class DashboardComponent implements AfterViewInit {

  displayedColumns = ['First Name', 'Last Name', 'Score'];
  dataSource = new MatTableDataSource<User>(ELEMENT_DATA);
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults 
    to lowercase matches
    this.dataSource.filter = filterValue;
  }
  constructor(private getFleetData: FleetDataService, private loaderService: 
   LoaderService) { }
   ngAfterViewInit() {
     this.dataSource.paginator = this.paginator;
     this.dataSource.sort = this.sort;
    }
  }

  const ELEMENT_DATA: User[] = 
  [{
    "FirstName": "Jill",
    "LastName": "Smith",
    "Score": "disqualified"
   }, {
    "FirstName": "Eve",
    "LastName": "Jackson",
    "Score": "94"
   }, {
    "FirstName": "John",
    "LastName": "Doe",
    "Score": "80"
   }, {"FirstName": "Adam",
    "LastName": "Johnson",
    "Score": "67"
   },{
     "FirstName": "Jill",
     "LastName": "Smith",
     "Score": "disqualified"
    }, {
     "FirstName": "Eve",
     "LastName": "Jackson",
     "Score": "94"
    }, {
     "FirstName": "John",
     "LastName": "Doe",
     "Score": "80"
    }, {
    "FirstName": "Adam",
    "LastName": "Johnson",
    "Score": "67"
   },{
    "FirstName": "Jill",
    "LastName": "Smith",
    "Score": "disqualified"
   }, {
    "FirstName": "Eve",
    "LastName": "Jackson",
    "Score": "94"
    }, {
    "FirstName": "John",
    "LastName": "Doe",
    "Score": "80"
   }, {
    "FirstName": ""Adam",
    "LastName": "Johnson",
    "Score": "67"
   },{
    "FirstName": "Jill",
    "LastName": "Smith",
    "Score": "disqualified"
   }, {
    "FirstName": "Eve",
    "LastName": "Jackson",
    "Score": "94"
   }, {
    "FirstName": "John",
    "LastName": "Doe",
    "Score": "80"
   }, {
    "FirstName": "Adam",
    "LastName": "Johnson",
    "Score": "67"
   }];

Also I see lot of problems in your code. I hope you did not miss anything for MatPaginator and MatSort.

这篇关于如何将从服务接收到的 json 数据传递到 angular 4 的角度材料中的组件中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:43