这是component.ts
export class RoleListComponent {
displayedColumns = ['roleAvatar', 'roleName']; // list of columns to show on UI
dataSource: RoleDataSource;
@ViewChild(MdSort) sort: MdSort;
constructor(private roleService: RoleService, private router: Router) { }
ngOnInit() {
this.dataSource = new RoleDataSource(this.roleService, this.sort);
}
}
export class RoleDataSource extends DataSource<any> {
roles: Observable<Role[]>;
constructor(private roleService: RoleService, private _sort: MdSort) {
super();
}
/** Connect function called by the table to retrieve one stream containing the data to render. */
connect(): Observable<Role[]> {
this.roles = this.roleService.getRoles();
const displayDataChanges = [
this.roles,
this._sort.mdSortChange,
];
return Observable.merge(...displayDataChanges).map(() => {
return this.getSortedData();
});
}
disconnect() { }
compare(a: string, b: string, isAsc: boolean) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
/** Returns a sorted copy of the database data. */
getSortedData(): Role[] {
let sortedData:Role[];
this.roles.subscribe(data => {
debugger
if (!this._sort.active || this._sort.direction == '') { return data; }
sortedData = data.sort((a, b) => {
let isAsc = this._sort.direction == 'asc';
switch (this._sort.active) {
case 'roleAvatar': return this.compare(a.name[0], b.name[0], isAsc);
case 'roleName': return this.compare(a.name, b.name, isAsc);
}
});
console.log(sortedData)
return sortedData;
});
return sortedData;
}
}
roleService.getRoles()
roleService
方法可返回Observable
类型的Role[]
。我已经合并了mdSort的observable和this.roles observable并返回了getSortedData()
。
现在在getSortedData()方法中,我订阅了this.roles observable以获取角色数组并对该数组进行排序并从subscribe内部返回。返回getSortedData()本身并且在调用此方法时它返回方法的return语句而不是subscribe的返回,因此排序的数据是未定义的,并且UI上没有记录。我很困惑怎么解决这个问题?
答案 0 :(得分:0)
尝试从Observable<Role[]>
返回getSortedData()
并在switchMap
中使用connect()
。
export class RoleDataSource extends DataSource<any> {
roles: Observable<Role[]>;
constructor(private roleService: RoleService, private _sort: MdSort) {
super();
}
/** Connect function called by the table to retrieve one stream containing the data to render. */
connect(): Observable<Role[]> {
this.roles = this.roleService.getRoles();
const displayDataChanges = [
this.roles,
this._sort.mdSortChange,
];
return Observable.merge(...displayDataChanges)
.switchMap(() => this.getSortedData());
});
}
disconnect() { }
compare(a: string, b: string, isAsc: boolean) {
return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
/** Returns a sorted copy of the database data. */
getSortedData(): Observable<Role[]> {
return this.roles.map(data => {
if (!this._sort.active || this._sort.direction == '') { return data; }
return data.sort((a, b) => {
let isAsc = this._sort.direction == 'asc';
switch (this._sort.active) {
case 'roleAvatar': return this.compare(a.name[0], b.name[0], isAsc);
case 'roleName': return this.compare(a.name, b.name, isAsc);
}
});
});
}
}