javascript - 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);
}));
}
解决方案
这是我的解决方案:
在我的服务中,我将我的数据变量设置为 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;
});
}
我希望这对其他人有帮助!
推荐阅读
- linux - 为什么编译器要添加额外的“sxtw”指令(进一步导致内核恐慌)?
- c# - 管理来宾可执行文件依赖项 - 本地 Service Fabric
- postgresql - 如何缩小一组 Postgres 行的范围,其中的值最接近特定值?
- hadoop - 如何从本地浏览器连接到谷歌云平台的外部IP
- excel - 使用串联重命名文件名
- python - 在 numpy 中如何在内部转换值
- vba - 多行文本框将第一行设置为粗体
- asp.net - 更新面板不起作用:接收错误:“响应”不是有效的脚本名称。名称必须以“.js”结尾
- c# - 将 Appium 测试结果记录到控制台
- python - 有没有办法置换矩阵的子集?