使用观测量和角度应用
问题描述:
过滤一个数组列表,我使用的观测在我的角度应用程序,它工作正常。但是,我遇到了一个有点混乱的情况。在一个组件,我成功订阅可观察到的,然后过滤结果,就像这样:使用观测量和角度应用
this.clientsService.getAll()
.subscribe(resRecordsData => {
this.records = resRecordsData;
this.inactiveRecords = this.records.filter(record => record.category && record.category.includes('inactive'));
this.records = this.inactiveRecords;
},
responseRecordsError => this.errorMsg = responseRecordsError);
然而,在另一组件,而我做几乎同样的事情,我正在印刷的错误控制台,上面写着:
例外:_this.records.filter不是一个函数
这是组件的样子:
optionReceived(option) {
console.log('Consulting: ' + option.toolbarLabel);
if (option.toolbarLabel === 'OT') {
console.log('Consulting: OT Filter Activated!');
this.clientService.getByCategory('consulting', 1, this.pagesize)
.subscribe(resRecordsData => {
this.records = resRecordsData;
this.OTRecords = this.records.filter(record => record.type && record.type.includes('OT'));
this.records = this.OTRecords;
},
responseRecordsError => this.errorMsg = responseRecordsError);
} else {
return this.records;
}
是什么在第二种情况下的问题?为什么我在那里得到错误,而不是在第一种情况下?
答
为什么不能过滤您订阅
this.clientsService.getAll()
.filter(record => record.category && record.category.includes('inactive'))
.subscribe(
resRecordsData => {
this.records = resRecordsData;
},
err => this.errorMsg = err
);
之前第一种情况下,我相信角使用RxJS,采取参考从http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-filter
答
这是因为异步特性,您可以使用skipWhile运营商
this.clientService.getByCategory('consulting', 1, this.pagesize)
.skipWhile(data => {
if(data.length) {
return false;
}
})
.subscribe(resRecordsData => {
this.records = resRecordsData;
this.OTRecords = this.records.filter(record => record.type && record.type.includes('OT'));
},
((responseRecordsError) => {this.errorMsg = responseRecordsError});
注:确保this.records=[];
被实例化
更新: 你不应该分配this.records=this.OTRecords;
认购里面,因为你得到了未定义的错误。
在过滤元件可能包含多个对象(阵列),而不是在第二种情况下
如果您在各种情况下悬停在this.records,你看到的数据类型?这两个例子有什么不同? – DeborahK
它们看起来是相同的:(属性)ConsultingComponent.records:任何[] – Muirik
“记录”被设置为在两个成分的空数组。 – Muirik