【发布时间】:2023-03-11 11:57:01
【问题描述】:
在问这个问题之前,我在这里做了一些研究,只发现有人询问是否将搜索值传递给休息 API 并返回结果。
我的问题完全不同。我有两个组件和一个服务:
- 一个搜索栏组件(负责在每个按键上获取用户输入)
- 一个应用列表组件(显示所有应用/仅显示过滤的应用)
- 一个应用服务,负责一次从后端获取所有用户应用,然后从搜索栏组件获取搜索输入并更新 behaviorSubject。
在任何时候,我都需要保留原始应用列表的副本以对其进行过滤。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, distinctUntilChanged, filter } from 'rxjs/operators';
import { Observable, BehaviorSubject } from 'rxjs';
import { Application } from '../models/apps.model';
@Injectable({
providedIn: 'root'
})
export class AppsService {
private appListSubject: BehaviorSubject<Application[]>;
private filteredAppListSubject: BehaviorSubject<Application[]>;
private appList: Observable<Application[]>;
constructor(private httpClient: HttpClient) {
this.appListSubject = new BehaviorSubject<Application[]>({} as Application[]);
this.filteredAppListSubject = new BehaviorSubject<Application[]>({} as Application[]);
this.appList = this.filteredAppListSubject.asObservable().pipe(distinctUntilChanged());
}
getApps(): Observable<Application[]> {
return this.httpClient.get('http://localhost:3000/api/user/apps').pipe(map(
(res: any) => {
this.setAppList = res;
return res;
}
));
}
public get getCurrentAppList() {
return this.appList;
}
public set setAppList(apps: Application[]) {
this.appListSubject.next(apps);
this.filteredAppListSubject.next(apps);
}
public searchApp(searchTerm: string) {
const filteredApps = this.appListSubject.pipe(filter(
(app: any) => {
if (app.name.includes(searchTerm)) {
return app;
}
}
));
this.filteredAppListSubject.next(filteredApps);
}
}
这是我当前的应用服务实现。
我的目标是让 applist 组件订阅 appList,每当搜索栏组件要求服务查找值时,applist 组件就会从 observable 中获取一个新的应用数组。
现在,由于管道函数返回一个 observable,我无法将结果添加为行为主体的下一个值。
我也想听听您对这个特定实现的看法。谢谢!
【问题讨论】:
标签: angular search angular-services behaviorsubject