首页 > 解决方案 > 从后端服务检索的对象未显示在 Angular html 页面上

问题描述

当搜索按钮按下并显示在角度 html 页面上时,我试图获取特定用户的用户权限数据,但是在将数据源放在 html 后我无法看到。在 console.log 中,JSON 对象成功显示。前端数据源的唯一问题,

我的服务订阅如下,

  import { SelectionModel } from '@angular/cdk/collections';
  import { Component, OnInit, ViewChild } from '@angular/core';
  import { MatDialog } from '@angular/material/dialog';
  import { MatTableDataSource } from '@angular/material/table';
  import { ManageuserService } from 'src/app/services/asset/manageuser.service';
  .
  .
  masterToggle() 
   {
    this.isAllSelected() ?
    this.selection.clear() :
    this.dataSource.data.forEach(row => this.selection.select(row));
  }
  dataSource: MatTableDataSource<any>;
 .
 .
 getUserPermisionsByUsernameSearch()
 {
  var param:string=this.permissionRequestUser;
    this.manageuserService.getUserPermissionApiMethod(param)
      .subscribe((data:any)=> {this.dataSource=new MatTableDataSource(data); console.log(data);});
  } 

在 console.log 中,我正在获取数据。我的前端 html 文件如下所示,

<br/>
    <div>
    <div>
        <button  mat-raised-button color="primary" (click)="getUserPermisionsByUsernameSearch()" >
                Search Permission</button>
 
 </div>
<br/> 
<div>
<mat-table #table [dataSource]="dataSource">
  <!-- ................................ ACCOUNT NO COLUMN .............................. -->  

  <ng-container matColumnDef="nUserId">
              <mat-header-cell style="min-width:150px;" *matHeaderCellDef> User ID</mat-header-cell>
              <mat-cell style="min-width:150px;" *matCellDef="let element"> {{element.nUserId}} 
</mat-cell>
            </ng-container>

  <ng-container matColumnDef="nPermissionId">
              <mat-header-cell style="min-width:150px;" *matHeaderCellDef> Permission Id</mat-header-cell>
              <mat-cell style="min-width:150px;" *matCellDef="let element"> {{element.nPermissionId}} </mat-cell>
            </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;"
                         (click)="selection.toggle(row)">
        </mat-row>

  </mat-table>

</div>

当页面加载时,我无法看到任何 API 结果,但在 console.log 中显示 JSON。

如何解决这里的问题?

标签: angular

解决方案


尝试如下更改您的代码。

//declare the dataSource variable
displayedColumns = [ 'nUserId','nPermissionId'];
  dataSource = new MatTableDataSource();

    getUserPermisionsByUsernameSearch(){
  let param:string=this.permissionRequestUser;
    this.manageuserService.getUserPermissionApiMethod(param)
      .subscribe((data:any)=> {
        this.dataSource.data=[data];
         console.log(data);
      });
  } 

推荐阅读