Angular Firestore自动完成实施

时间:2018-09-20 01:29:08

标签: angular autocomplete google-cloud-firestore

我的电影搜索TS中的Observable <[]>。subscribe似乎不起作用,因为每次我键入getItems()时,都不会执行。

更多背景:因此,我尝试使用Angular和Firestore为我的Web应用程序实现自动完成功能:当用户键入“ Ite”时,该应用程序在Firestore数据库中搜索标题以“ Ite”开头的所有项目并显示在页面上。

我的代码是基于此Firebase RealtimeDB教程构建的,并将更改应用于Firestore:https://angularfirebase.com/lessons/autocomplete-search-with-angular4-and-firebase/

电影搜索HTML:

<input type="text" (keydown)="searchMovie($event)" placeholder="search movies..." class="input">

<div *ngFor="let movie of movies">
  <h4>{{item?.title}}</h4>
  <p>
    {{item?.title}}
  </p>
</div>

<div *ngIf="item?.length < 1">
  <hr>
  <p>
    No results found :(
  </p>
</div>

电影搜索TS

import { Component, OnInit } from '@angular/core';
import { MoviesService } from '../../services/movies.service';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';


@Component({
  selector: 'app-movie-search',
  templateUrl: './movie-search.component.html',
  styleUrls: ['./movie-search.component.css']
})

export class MovieSearchComponent implements OnInit {
  movies;  

  startAt: BehaviorSubject<string|null> = new BehaviorSubject("");
  endAt: BehaviorSubject<string|null> = new BehaviorSubject("\uf8ff");

  constructor(private moviesSvc: MoviesService) { }


  searchMovie($event) {
    let q = $event.target.value
    this.startAt.next(q)
    this.endAt.next(q+"\uf8ff")
    console.log("startAt Looks like this", this.startAt);
    console.log("endAt Looks like this", this.endAt);
}

  ngOnInit() {
    //console.log("ngOnInIt was runing with ", this.startAt," as startAt")
    this.moviesSvc.getItems(this.startAt, this.endAt).subscribe(movies => this.movies = movies)

  }



}

movie.service TS

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument} from 'angularfire2/firestore';
import { Observable } from 'rxjs';
import { Item } from '../models/Item';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import "rxjs/add/operator/switchMap";
import "rxjs/add/observable/zip";

@Injectable()
export class MoviesService {

  itemsCollection:AngularFirestoreCollection<Item>;
  items:Observable<Item[]>;

  constructor(private afs: AngularFirestore) { 

  }

  getItems(start, end) {
    this.itemsCollection=this.afs.collection('items', ref => 
    ref
      .orderBy('title')
      .limit(5)
      .startAt(start)
      .endAt(end)  
  )

    console.log("itemsCollection is like", this.itemsCollection)

    this.items= this.itemsCollection.valueChanges()

    return this.items

  }


}

0 个答案:

没有答案