首页 > 解决方案 > Angular:如何订阅服务中不断变化的数据变量作为 Angular 材料表的数据源

问题描述

我需要一些指导。如何订阅不断更新的变量(searchData - 我的搜索结果的值)作为 Angular 材料表中使用的数据源?

我有一个table-datasource.ts文件,我想在其中订阅search.service.ts数据变量的搜索结果。

我想我可以使用BehaviorSubject,但我不确定如何正确实施。

我有以下基本设置table-datasource.ts file

dataSource = new MatTableDataSource<SearchRecord>();

ngOnInit() {
  this.dataSource.data = this.searchService.searchData; // this is where I would like to subscribe to the data changes
}

这是我的 search.service:

search(): Observable<SearchRecord[]>  {

return this.http
  .get<SearchRecord[]>(this.baseUrl + searchUrl + birthdate + partytype, { headers: httpHeaders })
  .pipe(
    retry(3),
    map((responseData: SearchRecord[]) => {
      let response: SearchRecord[] = [];
      this.searchData = responseData; // This is the variable I would like to subscribe to
      response = responseData;

      return response;
    }),
    catchError(errorRes => {
      // Send to analytics server
      return throwError(errorRes);
    }));
}

标签: javascriptangular

解决方案


这是我的解决方案:

在我的服务中,我将我的数据变量设置为 new ,并在我返回的数据上BehaviorSubject实现了发射器。.next()然后我简单地订阅了组件中的服务变量。

将变量设置为服务中的 BehaviorSubject:

searchData = new BehaviorSubject<SearchRecord[]>(null);

在我的服务中的方法调用中返回数据调用 .next:

map((responseData: SearchRecord[]) => {
  let response: SearchRecord[] = [];
  this.searchData.next(responseData); // Call .next on returned data
  response = responseData;

  return response;
}),

在我的组件中订阅服务变量:

  ngOnInit() {
    this.searchService.searchData.subscribe(data => {
      this.dataSource.data = data;
    });
  }

我希望这对其他人有帮助!


推荐阅读