我已经按照Angular Tour of Heroes和其他一些方法进行了教程,现在我正在尝试使用Angular 2构建应用程序。基本上当我们正在使用Subject监听更改时,我们可以等待几秒钟以便请求不会给网络带来负担。
这是我的代码:
import { Injectable } from '@angular/core';
import {Http} from "@angular/http";
import {Observable} from "rxjs/Observable";
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import {Employee} from "../employee";
@Injectable()
export class EmployeeSearchService {
private getPersonalURL:string = 'api/employee'; // I'm using mock, btw
constructor(private http:Http) { }
search(term:string): Observable<Employee[]> {
return this.http.get(`api/employee/?firstName=${term}`)
.map(response => response.json().data as Employee[])
.catch(this.handleError);
}
searchEmployees(term: Observable<string>): Observable<Employee[]> {
return term.debounceTime(200)
.distinctUntilChanged()
.switchMap(term => this.search(term)); // here is the error
}
private handleError(error: any): Promise<any> {
console.error('Error on EmployeeSearchService', error);
return Promise.reject(error.message || error);
}
}
这是调用组件:
import { Component, OnInit } from '@angular/core';
import {Subject} from "rxjs/Subject";
import { EmployeeService } from '../employee.service';
import { Employee } from '../employee'
import {EmployeeSharedService} from "../employee-shared.service";
import {EmployeeSearchService} from "../employee-search/employee-search.service";
@Component({
selector: 'employee-list',
providers: [ EmployeeService ],
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {
employees: Employee[];
selectedEmployee: Employee;
sortAsc: boolean;
searchQuery = new Subject<string>();
constructor(private employeeService:EmployeeService, private employeeSearchService:EmployeeSearchService, private employeeSharedService:EmployeeSharedService) {
this.sortAsc = true;
}
ngOnInit() { // called from here
this.employeeSearchService.searchEmployees(this.searchQuery)
.subscribe(result => {
this.employees = result;
if(!result) {
this.getAllEmployees();
}
});
}
getAllEmployees(): void {
// calling get all in service
}
}
有错误说
TypeError: term.debounceTime(...).distinctUntilChanged(...).switchMap is not a function
我错过了什么东西,比如进口或其他东西?因为确切的代码和导入与Angular Tour of Heroes教程和我的作品相同。但这个不是。
答案 0 :(得分:21)
您还需要添加switchMap
运算符:
import 'rxjs/add/operator/switchMap';
答案 1 :(得分:3)
这是罪魁祸首
searchQuery = new Subject<string>();
Subject
不是一个可观察对象,但你的功能是要求一个,所以要像这样修改
ngOnInit() {
this.employeeSearchService.searchEmployees(this.searchQuery.asObservable())...
}