我正在尝试为我的网络应用构建一个简单的搜索功能。 有关于如何使用实时数据库创建它的文档。
我需要做哪些更改才能在 firestore 上运行?
本教程取自此处https://angularfirebase.com/lessons/autocomplete-search-with-angular4-and-firebase/
它也有一个不错的视频:)
这是如何用实时数据库实现的:
#movies.service.ts
import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from '
angularfire2/database';
@Injectable()
export class MoviesService {
constructor(private db: AngularFireDatabase) { }
getMovies(start, end): FirebaseListObservable<any> {
return this.db.list('/movies', {
query: {
orderByChild: 'Title',
limitToFirst: 10,
startAt: start,
endAt: end
}
});
}
}
自动完成搜索组件
<h1>Movie Search</h1>
<input type="text" (keydown)="search($event)" placeholder="search
movies..." class="input">
<div *ngFor="let movie of movies">
<h4>{{movie?.Title}}</h4>
<p>
{{movie?.Plot}}
</p>
</div>
<div *ngIf="movies?.length < 1">
<hr>
<p>
No results found :(
</p>
</div>
TS
import { Component, OnInit } from '@angular/core';
import { MoviesService } from '../movies.service';
import { Subject } from 'rxjs/Subject'
@Component({
selector: 'movie-search',
templateUrl: './movie-search.component.html',
styleUrls: ['./movie-search.component.scss']
})
export class MovieSearchComponent implements OnInit {
movies;
startAt = new Subject()
endAt = new Subject()
constructor(private moviesSvc: MoviesService) { }
ngOnInit() {
this.moviesSvc.getMovies(this.startAt, this.endAt)
.subscribe(movies => this.movies = movies)
}
search($event) {
let q = $event.target.value
this.startAt.next(q)
this.endAt.next(q+"\uf8ff")
}
}
最佳答案
这与 Firestore 几乎相同。
这里是我刚刚编写的有效且经过测试的解决方案:
search.ts
import { Component } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
@Component({
selector: 'search',
templateUrl: 'search.html'
})
export class SearchComponent {
searchValue: string = "";
results: any;
constructor(public afs: AngularFirestore) {
}
search() {
let self = this;
self.results = self.afs.collection(`users`, ref => ref
.orderBy("username")
.startAt(self.searchValue.toLowerCase())
.endAt(self.searchValue.toLowerCase()+"\uf8ff")
.limit(10))
.valueChanges();
}
}
search.html
<div>
<input type="text" (keyup)="search()" [(ngModel)]="searchValue">
<div class="search-results">
<div class="search-result" *ngFor="let result of results | async">
{{ result.username }}
</div>
</div>
</div>
如果你需要更复杂的搜索,你可以使用 Algolia :
To enable full text search of your Cloud Firestore data, use a third-party search service like Algolia. Consider a note-taking app where each note is a document:
您会在 official firestore documentation 上找到更多信息
关于angular - 使用 angularfire2 和 firestore 创建自动完成搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47841119/