mat-table не будет заполняться данными из restservice - PullRequest
1 голос
/ 16 января 2020

Я получаю массив от моего restservice. Это работает, и некоторую информацию об ответе я печатаю на странице. Но, как ни странно, я не могу заполнить свою мат-таблицу и не знаю почему. Мат-таблица работала раньше, я просто неправильно помещаю в нее данные. Мы будем благодарны за любую помощь.

table-paginator-component.ts:

import {Component, OnInit, ViewChild} from '@angular/core';
import {MatPaginator} from '@angular/material/paginator';
import {MatTableDataSource} from '@angular/material/table';
import {HttpService} from '../http.service';
import { HttpClient } from '@angular/common/http';
import {AreaCode} from '../models/areacode';


@Component({
  // tslint:disable-next-line: component-selector
  selector: 'table-paginator',
  styleUrls: ['table-paginator.component.css'],
  templateUrl: 'table-paginator.component.html',
})
export class TablePaginatorComponent implements OnInit {
  displayedColumns: string[] = ['standort', 'stammnummer', 'bereich'];


  products = [];


  dataSource = new MatTableDataSource<any>(this.products);

  constructor(private httpClient: HttpClient) {
    this.getAreaCodes();
  }

  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
  }

  getAreaCodes() {






  this.httpClient.get('http://localhost:8080/phonenumbersmanagement/api/v1/areacodes/all')
.subscribe((res: 
any[]) => {
      console.log(res);
      this.products = res;
    });
  }

}

table-paginator.component. html:

<!-- <button (click)="getAreaCodes2()">GET /productss</button> -->

<ul>
  <li *ngFor="let product of products" >
-- id: {{product.id}}
-- name: {{product.title}}
-- base: {{product.base}}
  </li>
</ul> 

<div class="mat-elevation-z8">


<table mat-table [dataSource]="dataSource">

  <!-- Position Column -->
  <ng-container matColumnDef="standort">
    <th mat-header-cell *matHeaderCellDef> Standort </th>
    <td mat-cell *matCellDef="let element"> {{element.title}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="stammnummer">
    <th mat-header-cell *matHeaderCellDef> Stammnummer </th>
    <td mat-cell *matCellDef="let element"> {{element.title}} </td>
  </ng-container>

  <!-- Weight Column -->
  <ng-container matColumnDef="bereich">
    <th mat-header-cell *matHeaderCellDef> Bereich </th>
    <td mat-cell *matCellDef="let element"> {{element.title}} </td>
  </ng-container>

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

<mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
</div>

Токовый выход :

enter image description here

Ответы [ 4 ]

0 голосов
/ 16 января 2020

попробуй с this.products = res; this.datasource.data = res;

0 голосов
/ 16 января 2020

Измените метод getAreaCodes, как показано ниже,

getAreaCodes() {
  this.httpClient.get('http://localhost:8080/phonenumbersmanagement/api/v1/areacodes/all')
    .subscribe((res: any[]) => {
      this.products = res;
      this.dataSource = new MatTableDataSource(res);
    });
}

Обновите ваш mat-paginator с длиной, подобной привязке свойства.

<mat-paginator [length]="products.length" [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
0 голосов
/ 16 января 2020

Я думаю, что когда вы получаете данные из API и добавляете значение результата в переменную products, тогда переменная источника данных не обновляется.

Попробуйте использовать переменную products в html table tag-> [dataSource] = " продукты "

0 голосов
/ 16 января 2020

Эта штука сработала для меня. импортировать таблицу из angular / material и создать ее экземпляр, используя viewchild. получить ваши пользовательские данные и установить displayedColumns в ngOnInit(), в ngAfterContentChecked() вам нужно создать MatTableDataSource экземпляр и установить этот экземпляр на table.dataSource в ngAfterViewInit() проверьте ниже

import { MatTable, MatTableDataSource } from '@angular/material/table';

export class GetUserComponent implements OnInit {

@ViewChild(MatTable, {static:false}) table: MatTable<any>;
dataSource :any;


constructor(private appService:AppService){}

 ngOnInit() {
      this.appService.getUsers().subscribe(data => {
       this.userData= data;
      });
     this.displayedColumns = ['select','title','content'];
 }
 ngAfterViewInit() {

   this.table.dataSource = this.dataSource;
 }
 ngAfterContentChecked(){
    this.dataSource = new MatTableDataSource (this.userData);
  }
}

вы можете проверить мой стек, здесь https://stackblitz.com/edit/angular-dynamicexamples

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...