angular - 如何使用来自 Observable 的数据更新我的 Angular Table 数据源

标签 angular observable datasource mat-table angular-changedetection

我正在尝试在我的 Angular Material 表中显示从后端收到的数据。

只要我的 _timelogService.getAllTimelogs() 函数返回一个我硬编码到函数中的虚拟数据的 Observable,一切都会正常工作。一旦我向后端发出实际的 HTTP POST 请求 - 并返回该数据的 Observable - html 表就不会显示任何行,即使我的 dataSource 包含所需的数据。

当我使用 logData() 时,即使我使用实际的 Observable,它也会显示正确的数据。

我怀疑当数据源更新时我的 Angular 表没有更新。

还有其他人遇到过这样的问题吗?

export class OverviewComponent implements OnInit {

  displayedColumns: string[] = ['roomId', 'startTime', 'endTime', 
  'duration'];
  dataSource = new MatTableDataSource<TimeLogTable>();

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

  constructor(private _timelogService: TimelogService) {
    //In the Docs example the dummy data gets created here
  }

  ngOnInit(): void {
    this._timelogService.getAllTimelogs().subscribe(
      dataObs=>{
        console.log("Display received data");
        console.log(dataObs);
        this.dataSource.data = dataObs;
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      }
    )
  }

  logData(){
    console.log(this.dataSource);
  }
}

我的服务

getAllTimelogs(): Observable<TimeLogTable[]>{
  var timelogsArr: TimeLogTable[] = [];
  var timelogsArrDummy: TimeLogTable[] = [];

  //Call to backend
  this._http.get<any>('http://localhost:3000/gettimelogs?token=' + 
  localStorage.getItem('token'), this.httpOptions)
  .subscribe(
    res=>{
      //Create timeLogTable from json with backend response
      for (let i = 0; i < res.timelogs.length; i++) {
        timelogsArr.push({
          roomId: res.timelogs[i].roomId,
          startTime: new Date(res.timelogs[i].startTime),
          endTime: new Date (res.timelogs[i].endTime), 
          duration: "test"
        });
      }
    },
    err=>{
      //Error handling
    }
  );
  //Return the Observable - DOES NOT WORK
  return of (timelogsArr);

  /*
  //Return the dummy data as an Observable - DOES WORK
  //Dummy data
  timelogsArrDummy = [
  {roomId: 'kit_A', startTime: new Date(1631185600000), endTime: new 
  Date (1631185661311), duration: "test"},
  {roomId: 'din_A', startTime: new Date(1631185600000), endTime: new 
  Date (1631195661311), duration: "test"},
  {roomId: 'off_A', startTime: new Date(1631185600000), endTime: new 
  Date (1632185661311), duration: "test"},
  {roomId: 'kit_B', startTime: new Date(1631185600000), endTime: new 
  Date (1631885661311), duration: "test"},
  ]
  return of (timelogsArrDummy);
  */
}

这里是 console.log(dataObs) 的屏幕截图: enter image description here

最佳答案

我发现了导致我的问题的问题。 我的 getAllTimelogs() 函数首先返回一个空对象,然后用数据填充它。 MatTableDataSource 不知怎的无法处理这个问题。这是我的工作代码:

export class OverviewComponent implements OnInit, AfterViewInit {

  displayedColumns: string[] = ['roomId', 'startTime', 'endTime', 'duration'];
  dataSource = new MatTableDataSource<TimeLogTable>();

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: true }) sort: MatSort;  
  
  constructor(private _timelogService: TimelogService) { }

  timelogsArr: TimeLogTable[] = [];

  ngOnInit(): void {
    this._timelogService.getAllTimelogs().subscribe(
      res=>{
        //Create timeLogTable from json with backend response
        console.log("alert");
        for (let i = 0; i < res.timelogs.length; i++) {
          //Change the format of the data
          this.timelogsArr.push({
            roomId: res.timelogs[i].roomId,
            startTime: new Date(res.timelogs[i].startTime),
            endTime: new Date (res.timelogs[i].endTime), 
            duration: this.msToTime(res.timelogs[i].endTime - res.timelogs[i].startTime)
          });
        }
        //Update table datasource
        this.dataSource.data = this.timelogsArr;
      }
    );
  }

  ngAfterViewInit(): void {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

这里是 getAlltimelogs() 函数:

getAllTimelogs(): Observable<any>{
    return this._http.get<any>('http://localhost:3000/gettimelogs?token=' + localStorage.getItem('token'), this.httpOptions)
  }

感谢所有帮助过我的人。

关于angular - 如何使用来自 Observable 的数据更新我的 Angular Table 数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69120515/

相关文章:

angular - 如何设置 Angular Material 选项卡的样式?

javascript - 如何使用 Angular 进行 HTTP 基本身份验证

javascript - Angular 删除所有已完成的内容在没有刷新的情况下无法工作

retrofit - 仅当前面的可观察成功时才调用服务

java - JDBC 数据源的 JNDI 路径?

http - Angular 2 将 HTML 放入标签中

angular - 导入时将实现传递给 Angular 模块

scala - 使用 Monix Observable 处理错误的更好方法

java - quartz 触发器不触发

c# - DetailsView 的事件 "ItemUpdating"中的 OldValues 集合始终为空