Javascript 如何在角度中按列固定过滤器?
我正在写一个学习英语的项目。我的项目显示帖子。我想按id和标题过滤帖子。我需要post.service.ts中的过滤逻辑。我做了按ID过滤(效果很好),但按标题过滤效果很奇怪。如何修复标题过滤 所有项目 posts.service.ts:Javascript 如何在角度中按列固定过滤器?,javascript,angular,Javascript,Angular,我正在写一个学习英语的项目。我的项目显示帖子。我想按id和标题过滤帖子。我需要post.service.ts中的过滤逻辑。我做了按ID过滤(效果很好),但按标题过滤效果很奇怪。如何修复标题过滤 所有项目 posts.service.ts: import { HttpClient } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { Observ
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
export interface Post {
title: string,
body?: string;
userId?: number,
id?: number,
show?: any,
user?: string,
}
@Injectable({providedIn: 'root'})
export class PostService {
private _postsURL = "https://jsonplaceholder.typicode.com";
constructor(private http: HttpClient) {}
public fetchPosts(page: number, itemsPerPage: number, id: any, title: any): Observable<Post[]> {
let posts = this.http.get<Post[]>(`${this._postsURL}/posts`);
if (id) {
posts = this.http.get<Post[]>(`${this._postsURL}/posts?userId=${id}`)
}
if (title) {
posts = posts
.pipe(
map((posts: any) => {
return posts.map((post: any) => {
console.log(post.title.toUpperCase().includes(title.toUpperCase()))
return {
title: post.title.toUpperCase().includes(title.toUpperCase()) ? post.title : '',
}
})
})
);
}
return this.getPageItems(posts, page, itemsPerPage);
}
private getPageItems(posts: Observable<Post[]>, page: number, itemsPerPage: number): Observable<Post[]> {
return posts.pipe(
map(u => {
let startIndex = itemsPerPage * (page - 1);
return u.slice(startIndex, startIndex + itemsPerPage);
})
);
}
getById(id: number): Observable<Post> {
return this.http.get<Post>(`${this._postsURL}/posts/${id}`);
}
}
您可以按如下方式更新
if
条件:
if (title) {
posts = posts.pipe(
map((posts: any) => {
return posts.filter(item => item.title.includes(title));
})
);
}
“我想按列筛选帖子。”这是什么意思?过滤逻辑在哪里?我想按id和标题过滤帖子。过滤逻辑存在于serviceposts.service.ts中的fetchPosts()中为什么使用而不是来过滤数组?你没有过滤。您正在将某些元素的标题设置为空字符串。您正在开始加载所有元素。没有理由再次获取数据。您可以过滤前端中的元素,而无需重新提取。
if (title) {
posts = posts.pipe(
map((posts: any) => {
return posts.filter(item => item.title.includes(title));
})
);
}