我正在尝试使用RxJS从本地数组变量(因此不是通过网络,我已经获取数据并在启动时存储它)创建实时搜索,这就是我从中搜索数组的样子
[
{
"userId": 6130,
"friendId": 426,
"firstName": "hardik",
"lastName": "sa123",
"userName": "hardiksa123",
"image": "somelink",
"thumbs": [
{
"path": "somelink",
"size": "original"
},
{
"path": "somelink",
"size": "thumb_300x300"
}
],
"isBlocked": 0
},
{
"userId": 6130,
"friendId": 78294,
"firstName": "mayank",
"lastName": "vyas",
"userName": "mayank123",
"image": "",
"thumbs": [],
"isBlocked": 0
},
{
"userId": 6130,
"friendId": 941,
"firstName": "Sagar",
"lastName": "Sa",
"userName": "sagar",
"image": "",
"thumbs": [],
"isBlocked": 0
}
]
这是组件代码
const friendsFiltered = (friendList) => this.searchedFriends = friendList;
const getFullName = (friend) =>
`${friend.firstName} ${friend.lastName}`;
const isFriendMatching = (friend, searchText) =>
getFullName(friend).startsWith(searchText.toLowerCase());
const getMatchingFriends = (searchText) =>
of(this.allFriends.filter(friend => isFriendMatching(friend, searchText)));
console.log(getMatchingFriends);
this.nameSearch$ = this.search.valueChanges.pipe(
debounceTime(500),
map(searchText => searchText.trim()),
distinctUntilChanged(),
filter(searchText => searchText.length),
tap(c => console.log('search', c)),
switchMap(getMatchingFriends)
);
this.nameSearch$.subscribe(friendsFiltered);
如果我从管道中删除了switchMap
,它可以正常工作,并且错误属于getMatchingFriends
方法本身
注意:存在一个标题完全相同的问题,但是里面的内容完全不同,因此请注意。
编辑 这是更新一个代码后的整个代码
searchForn: FormGroup;
allFriends;
nameSearch$: Observable<any>;
searchedFriends: any[] = [];
constructor(
private friendService: FriendService,
private fb: FormBuilder,
) { }
ngOnInit() {
this.initialiseForm();
this.nameSearch$ = this.search.valueChanges.pipe(
debounceTime(500),
map(searchText => searchText.trim()),
distinctUntilChanged(),
filter(searchText => searchText.length),
tap(c => console.log('search', c)),
switchMap(this.getMatchingFriends)
);
this.nameSearch$.subscribe(this.friendsFiltered);
}
initialiseForm() {
this.searchForn = this.fb.group({
searchName: [],
});
}
get search() { return this.searchForn.get('searchName'); }
friendsFiltered = (friendList) => {
this.searchedFriends = friendList;
console.log('sf', this.searchedFriends);
}
getFullName = (friend) => `${friend.firstName.toLowerCase()} ${friend.lastName.toLowerCase()}`;
isFriendMatching = (friend, searchText) =>
this.getFullName(friend).includes(searchText.toLowerCase());
getMatchingFriends = (searchText) =>
of(this.allFriends.filter(friend => this.isFriendMatching(friend, searchText)));
getAllFriends() {
this.friendService.getFriends().then((friends: any) => {
this.allFriends = friends.friends;
}).catch((err) => {
// Handle error
});
}