首页 > 解决方案 > MonoTypeOperatorFunction<{}> Rxjs6 类型上不存在属性“distinctUntilChanged()”

问题描述

我正在尝试创建一个搜索服务以在输入中进行实时搜索。我有 search.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

import { Observable } from 'rxjs';
import { map, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SearchService {

  baseUrl: string = 'https://api.cdnjs.com/libraries';
  queryUrl: string = '?search=';

  constructor(private http: Http) { }

  search(terms: Observable<string>) {
    return terms.pipe(debounceTime(400)
      .distinctUntilChanged()
      .switchMap(term => this.searchEntries(term)));
  }

  searchEntries(term) {
    this.http.get(this.baseUrl + this.queryUrl + term).pipe(map(res => {
      res.json();
    }))
  }
}

app.component.ts

import { Component } from '@angular/core';
import { SearchService } from './search.service';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [SearchService]
})
export class AppComponent {
  results: Object;
  searchTerm$ = new Subject<string>();

  constructor(private searchService: SearchService) {
    this.searchService.search(this.searchTerm$)
      .subscribe(results => {
        this.results = results.results;
      });
  }
}

我在search.service.ts MonoTypeOperatorFunction<{}> 类型上不存在 Property 'distinctUntilChanged()' 中遇到问题。我怎样才能解决这个问题?请提出建议。

编辑 下面的代码解决了这个问题。

search(terms: Observable<string>) {
        return terms.pipe(debounceTime(400),
            distinctUntilChanged(),
            switchMap(() => interval(50), term => this.searchEntries(term)));
    }

你可以在 github 上访问我的这个项目的代码

标签: typescriptangular6rxjs6

解决方案


您的呼叫pipe不正确。管道中的操作符应该是分开的,而不是被链接.

return terms.pipe(debounceTime(400),
  distinctUntilChanged(),
  switchMap(term => this.searchEntries(term)));

推荐阅读