使用switchMap可观察Angular2过滤器

时间:2016-09-07 14:43:16

标签: asp.net-web-api angular typescript

我使用Angular2和WebAPI使用众多Angular2教程中描述的方法进行术语搜索。

在我的服务中:

search(term: string): Observable<UserList[]> {
    return this.http.get(this.userSearchUrl + term)
        .map((response: Response) => response.json())
        .catch(this.handleError);
}

在我的组件中:

ngOnInit(): void {
    this.users = this.searchTermStream
        .debounceTime(300)
        .distinctUntilChanged()
        .switchMap((term: string) =>
            term ? this.userService.search(term) : Observable.of<UserList[]>([]))
        .catch(error => {
            console.log(error);
            return Observable.of<UserList[]>([]);
        });
}

我想在服务方面做的是跟踪上次搜索。因此,如果我的初始搜索是&#34; b&#34;然后我搜索&#34; bo&#34;您不必再调用WebAPI,因为我们已经拥有了我们需要的结果,我们只需要进一步过滤。我认为使用Observables这样做是不可能的,因为你订阅了一个流,但我还不太了解Observables。我想也许做承诺可能会更容易,但我不知道如何处理它的组件方面,如Subject()和switchMap()似乎只适用于Observables

这就像我想在服务方面使用的那样:

searchPromise(term: string): Promise<UserList[]> {
    if (this.lastUsedTerm.length > 0 && term.indexOf(this.lastUsedTerm) == 0) {
        this.lastUsedSearch = this.lastUsedSearch.then(x => x.filter(z => z.firstName.startsWith(term)));
    }
    else {
        this.lastUsedSearch = this.http.get(this.userSearchUrl + term)
            .toPromise()
            .then((response: Response) => response.json())
            .catch(this.handleError);
    }

    this.lastUsedTerm = term;
    return this.lastUsedSearch.then(x => x.filter(z => z.firstName.startsWith("bob")));
}

0 个答案:

没有答案