mat-table 不会从 api 加载值。 Api 工作正常

mat-table doesn't load values from api. Api is working fine

我在这个网站上找到了答案,我得到了一些答案,但我没有解决我的问题。我在这里看到和阅读了很多东西,但什么都没有。

我不会用我的代码填充 mat-table。这是我的 html.

<div>
  <table mat-table [dataSource] = "dataSource" class="mat-elevation-z8">

     <ng-container matColumnDef="codigo">
       <th mat-header-cell *matHeaderCellDef> Codigo </th>
       <td mat-cell *matCellDef="let oper"> {{oper.operatorId}} </td>
    </ng-container>

    <ng-container matColumnDef="nome">
      <th mat-header-cell *matHeaderCellDef> Nome </th>
      <td mat-cell *matCellDef="let oper"> {{oper.name}} </td>
    </ng-container>

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

当我 运行 我的 APIPostman 我得到这个

"itens": [
        [
            {
                "operatorId": "819ee9cc-70b6-44dc-b9e8-afff8705142c",
                "name": "Paulo Correa"
            },
            {
                "operatorId": "ccad3b40-c227-425e-b3b1-feedf6cfac2e",
                "name": "Catarina Silva"
            },
            {
                "operatorId": "68781a7b-ac4c-4a85-9f93-36dc5d65d1af",
                "name": "José da Silva"
            }
        ]
    ],

好的,我的 API 正在工作。组件是

import { Component, OnInit } from '@angular/core';
import { OperatorService } from '../operator.service';
import { Operation, Itens } from '../model/operators/operations';

export interface getOperator{
  Id: string;
  Name: string;
}

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

export class OperatorsComponent implements OnInit {

   displayedColumns: string[] = ['codigo', 'nome'];

    public message: string;
    public dataSource: Itens[];

    constructor( private _operService: OperatorService) 
    {}    

  ngOnInit() {

  this._operService
      .getAll<Operation>()
      .subscribe((data: Operation) => {
        debugger;
        this.dataSource = data.itens;
      });
  }
}

伊腾斯是谁?这是我的 class

export class Operation{
    error: boolean;
    itens: Array<Itens>;
    message: string;
}

export class Itens{
    objectId: string;
    name: string;
}

和我的服务

    import { Injectable } from '@angular/core';

    import { HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
    import { Observable } from 'rxjs';

    import { Configuration } from './app.constants';

    @Injectable({
      providedIn: 'root'
    })
    export class OperatorService {

      private actionUrl: string;

        constructor(private http: HttpClient, private _configuration: Configuration) {
            this.actionUrl = _configuration.ServerWithApiUrl + 'Operators/';
        }

        public getAll<T>(): Observable<T> {
          return this.http.get<T>(this.actionUrl);
      }

      public getSingle<T>(id: number): Observable<T> {
          return this.http.get<T>(this.actionUrl + id);
      }

      public add<T>(itemName: string): Observable<T> {
          const toAdd = JSON.stringify({ ItemName: itemName });

          return this.http.post<T>(this.actionUrl, toAdd);
      }

      public update<T>(id: number, itemToUpdate: any): Observable<T> {
          return this.http
              .put<T>(this.actionUrl + id, JSON.stringify(itemToUpdate));
      }

      public delete<T>(id: number): Observable<T> {
          return this.http.delete<T>(this.actionUrl + id);
      }
    }

@Injectable()
export class CustomInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

        req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
        console.log(JSON.stringify(req.headers));
        return next.handle(req);
    }
}

这里是断点的结果。我有价值

我的 data.itens return 值,但我的 mat-table 为空或空的。我做错了什么?

P.S. 在这里我没有修复: 我关注了这个 link Using a static array as datasource for mat-table 但我没有解决这个问题。

我怀疑这个话题是否重复,我 ban,但我得到的所有答案都没有解决我的问题,所以我创建了一个关于这个问题的新话题.

EDIT1

我按照 Antoniosss 发布的示例进行操作,代码(组件)是这样的

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

export interface getOperator{
  Id: string;
  Name: string;
}

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

export class OperatorsComponent implements OnInit {

   displayedColumns: string[] = ['codigo', 'nome'];

    public message: string;
    //public dataSource: Itens[];
    public dataSource=new MatTableDataSource<Itens[]>();

    constructor( private _operService: OperatorService) 
    {}    

  ngOnInit() {

  this._operService
      .getAll<Operation>()
      .subscribe((data: Operation) => {
        debugger;
        this.dataSource.data = data.itens;
      });
  }
}

这是错误:

[ts] Type 'Itens[]' is not assignable to type 'Itens[][]'. Type 'Itens' is not assignable to type 'Itens[]'. Property 'includes' is missing in type 'Itens'. (property) OperatorsComponent.dataSource: MatTableDataSource

我愿意

public dataSource=new MatTableDataSource<Itens>;

以后

  this._operService
      .getAll<Operation>()
      .subscribe((data: Operation) => {
        this.dataSource.data = data.itens;
      });

使用这些类似代码段的表格从未遇到过问题。

我是这样解决的。从 API 返回的 json 是错误的。在其他 Array 中有一个 Array,如下所示:

"itens": [
        [
            {
                "operatorId": "819ee9cc-70b6-44dc-b9e8-afff8705142c",
                "name": "Paulo Correa"
            },
            {
                "operatorId": "ccad3b40-c227-425e-b3b1-feedf6cfac2e",
                "name": "Catarina Silva"
            },
            {
                "operatorId": "68781a7b-ac4c-4a85-9f93-36dc5d65d1af",
                "name": "José da Silva"
            }
        ]
    ],

所以创建 api 的朋友修改了它。现在我开始使用来自 api 的数据填充我的 mat-table。我正在回答关闭此 post。