可观察对象、数组和过滤
observables, arrays and filtering
使用 angular 8,rxjs 6.5.2
我有一个 http 调用,returns 可观察到
{
'A': {name: 'A', type:'1'},
'B': {name: 'B', type:'2'},
'C': {name: 'C', type:'2'}
}
我把这个调用存储在data$
我想在 angular 表格中显示所有类型“2”。我知道要将对象转换为数组,我可以使用 Object.values(data)
那么如何将 observable 转换为一个数组,然后可以对其进行过滤并改回 observable?
我试过这个代码
this.myService.getPeople().subscribe(data => {
const items = Object.values(data).filter(
(item: any) => item && item.type === '2'
);
this.data$ = of(items);
});
但表单从不更新或刷新
我是不是遗漏了什么明显的东西?
您将需要使用地图运算符。
this.data$ = this.myService.getPeople().pipe(map(data => {
const items = Object.values(data).filter(
(item: any) => item && item.type === '2'
);
return items;
});
我假设您的组件使用 ChangeDetectionStrategy.OnPush。
在这种情况下,您需要将 ChangeDetectorRef 添加到组件的构造函数参数中:
constructor(changeDetectorRef: ChangeDetectorRef, ...) {
...
}
然后将您的数据获取函数更改为:
this.myService.getPeople().subscribe(data => {
const items = Object.values(data).filter(
(item: any) => item && item.type === '2'
);
this.data$ = of(items);
this.changeDetectorRef.markForCheck();
});
使用 angular 8,rxjs 6.5.2
我有一个 http 调用,returns 可观察到
{
'A': {name: 'A', type:'1'},
'B': {name: 'B', type:'2'},
'C': {name: 'C', type:'2'}
}
我把这个调用存储在data$
我想在 angular 表格中显示所有类型“2”。我知道要将对象转换为数组,我可以使用 Object.values(data)
那么如何将 observable 转换为一个数组,然后可以对其进行过滤并改回 observable?
我试过这个代码
this.myService.getPeople().subscribe(data => {
const items = Object.values(data).filter(
(item: any) => item && item.type === '2'
);
this.data$ = of(items);
});
但表单从不更新或刷新
我是不是遗漏了什么明显的东西?
您将需要使用地图运算符。
this.data$ = this.myService.getPeople().pipe(map(data => {
const items = Object.values(data).filter(
(item: any) => item && item.type === '2'
);
return items;
});
我假设您的组件使用 ChangeDetectionStrategy.OnPush。
在这种情况下,您需要将 ChangeDetectorRef 添加到组件的构造函数参数中:
constructor(changeDetectorRef: ChangeDetectorRef, ...) {
...
}
然后将您的数据获取函数更改为:
this.myService.getPeople().subscribe(data => {
const items = Object.values(data).filter(
(item: any) => item && item.type === '2'
);
this.data$ = of(items);
this.changeDetectorRef.markForCheck();
});