gpt4 book ai didi

angular - switchMap 不是函数

转载 作者:太空狗 更新时间:2023-10-29 17:29:17 28 4
gpt4 key购买 nike

我遵循了教程 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 教程相同,而我的作品。但这个不是。

最佳答案

您还需要添加 switchMap 运算符:

import 'rxjs/add/operator/switchMap';

关于angular - switchMap 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43569444/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com