After completing the Angular Tour of Heroes tutorial and some others, I decided to start building apps with Angular 2. One important thing I learned is that when we're listening for changes with a Subject, it's good practice to wait for a few seconds before making a request in order to avoid burdening the network.
Below is the code snippet I'm currently working on:
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'; // Using mock data for now
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)); // Error occurs here
}
private handleError(error: any): Promise<any> {
console.error('Error on EmployeeSearchService', error);
return Promise.reject(error.message || error);
}
}
And here's the component where the service is being called:
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() { // Call initiated from here
this.employeeSearchService.searchEmployees(this.searchQuery)
.subscribe(result => {
this.employees = result;
if(!result) {
this.getAllEmployees();
}
});
}
getAllEmployees(): void {
// Function to retrieve all employees from the service
}
}
The error message received is:
TypeError: term.debounceTime(...).distinctUntilChanged(...).switchMap is not a function
I'm wondering if there's something missing in my code, such as an import statement or something else? The code structure and imports are similar to those in the Angular Tour of Heroes tutorial which worked fine for me. Any insights would be appreciated!