首页 > 解决方案 > UserDataSource 在 Angular 中没有数据属性

问题描述

我正在尝试按照本指南将多选添加到 Angular Material 表中。它data在 masterToggle 中引用,但我的 UserDataSource 中没有该属性。解决此问题的正确方法是什么?

我的组件

dataSource: UserDataSource;

ngOnInit() {
    this.dataSource = new UserDataSource(this.svc);
    this.dataSource.loadCompanies(this.lgid);
}
masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
}

用户数据来源:

export class UserDataSource implements DataSource<Company> {

private CompanyModelsSubject = new BehaviorSubject<Company[]>([]);
private loadingSubject = new BehaviorSubject<boolean>(false);
public loading$ = this.loadingSubject.asObservable();

constructor(private svc: GreencardService) { }

connect(collectionViewer: CollectionViewer): Observable<Company[]> {
    return this.CompanyModelsSubject.asObservable();
}

disconnect(collectionViewer: CollectionViewer): void {
    this.CompanyModelsSubject.complete();
    this.loadingSubject.complete();
}

loadCompanies(lgid)
{
    this.loadingSubject.next(true);
    this.svc.getCompanies(lgid).pipe(
        catchError(() => of([])),
        finalize(() => this.loadingSubject.next(false))
    ).subscribe(x => { this.CompanyModelsSubject.next(x);});
}

标签: angular

解决方案


我相信您正在遵循的示例是使用MatTableDataSource具有公共吸气剂的类data...

get data() { return this._data.value; }

而私有变量_dataBehaviorSubject带有初始化数据的。

 constructor(initialData: T[] = []) {
    super();
    this._data = new BehaviorSubject<T[]>(initialData);
    this._updateChangeSubscription();
  }

因为您创建了自己的类,所以您需要实现一个类似的公共 getter... 可能如下所示。

get data() {return this.CompanyModelsSubject.value; }

https://github.com/angular/material2/blob/bc8fc75bf8af82378077d7c2277e31a1dcd6aac9/src/lib/table/table-data-source.ts#L62


推荐阅读