mat-table,dataSource - 如何从两个订阅的结果创建dataSource

时间:2018-06-04 20:42:35

标签: angular rxjs material-design google-cloud-firestore angularfire2

我想连接两个服务的结果: - fetchUserData - fetchResultData 到一个dataSource,我将用它来创建我的mat-table。

dataSource有两个字段: - 用户 - >串, - 点 - >号。

组件文件:

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

export class TestComponent implements OnInit, OnDestroy, AfterViewInit {

  displayedColumns = ['User', 'Points'];

  dataSource = new MatTableDataSource();

  private exDisplayNames: Subscription;
  users: UserModel[];

  private exDisplayResults: Subscription;
  results: ResultModel[];


  @ViewChild(MatSort) sort: MatSort;

  constructor(private testService: TestService) {   }

  ngOnInit() {
    this.exDisplayNames = this.testService.userDataChanged.subscribe((userNameData: UserModel[]) => {
      this.users = userNameData;
    });
    this.testService.fetchUserData();

    this.exDisplayResults= this.testService.resultDataChanged.subscribe((resultsData: ResultModel[]) => {
      this.results = userNameData;
    });
    this.testService.fetchResultData();

  }

  ngAfterViewInit() {
    this.dataSource.data = this.createDisplaySource();
    this.dataSource.sort = this.sort;
  }

createDisplaySource() {
  let tempResult = 0;
  const tempArray: any[] = [];

  for( const result of this.results) {
    for (const user of this.users) {
        if(user.id === match.id && user.prediction === result.result) {
        tempResults += 1;
        }
     }
  }
  tempArray.push({
        user: match.user,
        points: tempResults
        });

 return tempArray;

  }

  ngOnDestroy() {

    if (this.exDisplayNames) {
        this.exDisplayNames.unsubscribe();
    }

   if (this.exDisplayResults) {
        this.exDisplayResults.unsubscribe();
    }
  }

 }

模型文件:

 export interface UserModel {
    user: string;
    prediction: number;
    id: string;
}

 export interface ResultModel {
    result: number;
    id: string;
}

我认为,我的实施不正确。但也许,有任何模式可以将多个服务结果组合到一个mat-table中。我需要在dataSource中使用它(不仅仅是在表中显示),因为我想要那些数据。

0 个答案:

没有答案