Reputation: 828
Does anybody know why this filter after mapping, is not working?
When I do this:
this.cacheService.getMainCache().pipe( map(val => val.list)).subscribe((val) => {
console.log(val);
}, (error) => {
console.log('Error: ', error);
});
I need to filter this array and return only one, the one with the name property equal to some string, when I add the filter operator to the pipe nothing happens, I suppose nothing is filtered:
this.cacheService.getMainCache().pipe(map(val => val.list), filter((item: any) => item.name == 'profile')).subscribe((val) => {
console.log(val);
}, (error) => {
console.log('Error: ', error);
});
What am I doing wrong here?
Upvotes: 2
Views: 1646
Reputation: 2597
@devnosaur, Your most recent update where you chain pipes, the chained pipes are actually unnecessary. The most effective change you made was switchMap(val => from(val.list)
which has the same effect as
map(val => val.list),
concatAll()
that A. Winnen recommended above. In my opinion, even though it is an extra line, doing map then concatAll() communicates much better, whereas using a flattening operator (switchMap) on a created observable (from) seems hacky.
Upvotes: 0
Reputation: 828
Thank you all, but I managed to solve it chaining the pipes, my mistake:
this.cacheService.getMainCache()
.pipe(switchMap((val) => from(val.list)))
.pipe(filter((item: any) => item.name == 'profile'))
.subscribe((val) => {
console.log(val);
}, (error) => {
console.log('Error: ', error);
});
Upvotes: 2
Reputation: 1698
The problem with your snippet is the type of item. You expect the filter function to filter the items. But in your case, item is the whole array itself. Since the array does not have a property "name", nothing is showing at the subscriber. I suggest to use proper typing.
you have two options:
this.cacheService.getMainCache().pipe(
map(val => val.list.filter((item: any) => item.name == 'profile'))
).subscribe((val) => {
console.log(val);
}, (error) => {
console.log('Error: ', error);
});
this.cacheService.getMainCache().pipe(
map(val => val.list),
concatAll(),
filter((item: any) => item.name == 'profile')),
toArray()
).subscribe((val) => {
console.log(val);
}, (error) => {
console.log('Error: ', error);
});
Upvotes: 3
Reputation: 6016
try this @devnosaur, it may solve your issue. for more about Observable filter have a look here
this.cacheService.getMainCache().map((value: any)=> value.filter(val=> val.name === 'profille')).subscribe((val) => {
console.log(val);
}, (error) => {
console.log('Error: ', error);
});
Upvotes: 1