无法使用可观察角度更新材料表数据源

时间:2019-11-29 09:38:51

标签: angular angular-material observable behaviorsubject subject-observer

我想在Angular 7中制作一个动态材质表

该表首次(ngOnInit)将显示数据库中的所有用户(使用服务中的getUsers()方法)。另一种可能的环境是用户单击按钮时。在这种情况下,该表将显示较少的用户(使用服务中的getLessUsers()方法)作为过滤器功能。

结构就是这个(不能更改),并且两个组件在同一视图中:

  • 具有表的主要组件:users-list.component.ts
  • 带有按钮的组件:less-users.component.ts
  • 两个组件的公用服务:user.service.ts

主要组件正常工作,可以从数据库中获取所有用户。但是当我单击按钮时,表格不会更新。

我认为我必须使用Observables来实现Material表的通用数据源。但是我无法使其正常工作。

user-list.component.ts

export class UsersListComponent implements OnInit {

users: User[] = [];
users$: Observable<User[]>;
paginator: any;

dataSource = new MatTableDataSource(this.users);
displayedColumns: string[] = ['name','user'];

@Input() user: UserService;
@ViewChild(MatSort) sort: MatSort;

constructor(private userService: UserService,
  private activatedRoute: ActivatedRoute, private router: Router) { }

ngOnInit() {

  this.activatedRoute.paramMap.subscribe( params => {

  let page: number = +params.get('page');

  if(!page)
    page = 0;

  this.userService.getUsers(page)
  .subscribe(response => {
      this.users = response.content as User[];
      this.paginator = response;

    });

    // Should I use these lines?
    //this.users$ = this.userService.users$;
    //this.users$.subscribe(users=> this.users= users);

  });

  this.dataSource.sort = this.sort;

}

users.service.ts

export class UserService {

    users: User[];
    users$: Subject<User[]> = new Subject<User[]>();

    //GET ALL USERS
    getUsers(page: number): Observable<any> {
    return this.http.get(this.urlEndPoint + '/page/' + page).pipe(
      tap( (response: any) => {
        (response.content as User[]).forEach(user => {
          console.log(user.name);
        });
      }),
      map( (response: any) => {
          (response.content as User[]).map(user=> {
            return user;
          });
          return response;
      })
    );
  }

  //GET LESS USERS
  async getUsersFiltered(filter: Filter) {
      return await this.http.post<User[]>(this.urlEndPoint + '/filters', filter, {headers: 
  this.httpHeaders}).pipe(
       map( (response: any) => {

            this.setArrayUsersFiltered(response as User[]);
            //console.log("CONTENT" + this.getArrayUsersFiltered().subscribe())
            return response;
        })
      );
   }

  //OBSERVABLE METHODS (NOT SURE HOW TO USE THEM)
  setArrayUsersFiltered(users: User[]) {

    this.users= uers;
    this.users$.next(this.users);
  }

  getArrayUsersFiltered(): Observable<User[]> {
    return this.users$.asObservable();
  }

less-users.component.ts

async applyFilters(dataSource: MatTreeFlatDataSource<TodoItemNode, TodoItemFlatNode>) {
    await this.userService.getUsersFiltered(this.filtersSelected).then(
      () => console.log("OBSERVABLE: " + this.userService.getArrayUsersFiltered())  //OK. Data received as expected
);

以下是显示材料表但未更新的主要组件的HTML:

users-list.component.html

<table mat-table [dataSource]="users" matSort style="margin-bottom: 1%">

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
    <td   mat-cell *matCellDef="let user"> {{user.name}} </td>
  </ng-container>

<...>
<...>

Stackblitz链接:https://stackblitz.com/edit/angular-frf8iy?file=src%2Fapp%2Fusers-list.component.html

有解决方案吗?谢谢。

0 个答案:

没有答案