Angular Material + GAPI:表显示行,但是有空单元格

时间:2018-03-18 17:30:21

标签: angular typescript material gapi

我正在整合角度素材和Google API。我想在表格中显示api的响应。问题是mat-table行的mat-cell没有填充,但显示了行。这是我的表:

    export interface User { name: string; age: number; city: string; }

这是我创建的界面:

    export class UsertableComponent implements OnInit, OnChanges {
  @Input() apiReady: boolean;

  dataSource: UserDataSource;
  displayedColumns = ['name', 'age', 'city'];

  constructor(private userService: UserService) {

  }

  ngOnInit() {

  }

  ngOnChanges(changes: SimpleChanges) {
    if (this.apiReady) {
      this.dataSource = new UserDataSource(this.userService);
    }
  }
}

export class UserDataSource extends DataSource<any> {
  constructor(private userService: UserService) {
    super();
  }

  connect(): Observable<User[]> {
    return this.userService.getUsers();
  }

  disconnect() {

  }
}

这是与表关联的组件:

export class UserService {
  private serviceUrl = environment.apiUrl + '/getcust/';
  private apiLoaded = false;
  constructor(private http: HttpClient) { }

  getUsers(): Observable<User[]> {
    /* // THIS WORKS!!!
        const u: User = {
          'name': 'ss',
          'city': 'città',
          'age': 3
        };
        return Observable.create(observable => {
          observable.next([u]);
          observable.complete();
        });
     */

    return Observable.create(observable => { // THIS DOESN'T WORK
      return gapi.client.directory.users.list({
        'customer': 'my_customer',
        'maxResults': 1,
        'orderBy': 'email'
      }).then(response => {

        const u: User = {
          'name': response.result.users[0].name.fullName,
          'city': 'citta',
          'age': 3
        };

        observable.next([u]);
        observable.complete();
      });
    });
  }
}

最后,这里是噩梦。调用gapi并返回数据的服务。我可以确保api响应,特别是这行代码 response.result.users [0] .name.fullName 对应一个带有值的字符串对象。

float tiv = Float.parseFloat(tiva);     // tiva is a global, String type variable

正如您在评论中看到的那样,评论的行有效,其他则没有。

Result with empty cells

Result with populated cells, without calling GAPI

1 个答案:

答案 0 :(得分:0)

解决方案是:

导入此内容:

constructor(private cd: ChangeDetectorRef) {
  }

组件的构造函数:

    ngOnInit() {
    this.dataSource = new UserDataSource();
}

在ngInit中初始化数据源:

{{1}}

使用 BehaviorSubject (以及方法 asObservable )可以随时更改数据源的内容,但是当表格中的数据发生变化时,请不要忘记致电:

<强> this.cd.detectChanges();

更新单元格内容