我正在尝试过滤具有与此类似结构的对象数组:
posts = [
{
title: 'post 1 title',
location: 'Location 1'
},
{
title: 'post 2 title',
location: 'Location 2'
},
{
title: 'post 3 title',
location: 'Location 3'
}
]
我正在使用字符串数组(下面)过滤这个对象数组(上面)
locations = [
'Location 1',
'Location 2',
'Location 3'
]
它应该如何工作:我在浏览器中输入一个'标签'样式输入框,我想要多个位置,它应该显示位置属性与位置数组中位置'标签'匹配的帖子。
最初显示所有帖子(这很好),然后当我输入标签时,我能够在日志中获取过滤后的对象,这表明它们似乎是根据我的输入进行过滤。但是帖子循环的html没有显示相关的帖子。
我正在使用firebase存储帖子,并调用我的服务,该服务返回ngOnInit()
上的所有帖子
ngOnInit() {
this._tags = [];
this._postService.getAllPosts().subscribe(posts => {
this._posts = posts;
});
}
HTML:
<!--input *edited some stuff out like the add tag function. 'term' model gets pushed into the _tags array on enter or click etc-->
<input type="text" placeholder="Search" [(ngModel)]="term [ngModelOptions]="{standalone: true}">
<!--tag list, shows tags that have been searched-->
<div class="tag" *ngFor="let t of _tags">{{t}}</div>
<!filtered post list-->
<div *ngFor="let post of _posts | tagsearchfilter:_tags">
<h4>{{post.title}}</h4>
</div>
...
管道过滤器:
import { Pipe, PipeTransform } from '@angular/core';
import { PostService } from '../../services/post/post.service';
@Pipe({
name: 'tagsearchfilter'
})
export class TagSearchFilterPipe implements PipeTransform {
transform(posts: any, tags: any): any {
let rposts = [];
if (tags === undefined || tags.length === 0 ) {
return posts;
}
posts = posts.filter(function(post){
tags.forEach(tag => {
if (
post.location.toLowerCase().includes(tag.toLowerCase())
) {
rposts.push(post);
console.log('Post location: ' + post.location + ' Tag: ' + tag);
}
});
posts = rposts;
console.log(posts);
return posts;
});
}
}