【问题标题】:TypeError: Cannot read property 'pipe' of undefinedTypeError:无法读取未定义的属性“管道”
【发布时间】:2019-06-10 11:49:41
【问题描述】:

我正在使用 RxJS 在 Angular 中编写实时搜索功能。我收到一些错误,因为 TypeError:无法读取未定义的属性“管道”。 我正在使用 Angular 7,并且尝试了 StackOverflow 中的不同代码示例,但无法解决此问题。

app.Component.html

<input type='text' class="form-control input-txt-start" placeholder="Search Domain Name" name="domainId" (keyup)='getSearchResults(searchTerm$.next($event.target.value))'>

<ul *ngIf="results">
    <li *ngFor="let result of results | slice:0:9">
        {{ result}}
    </li>
</ul>
<p *ngIf="error">
    {{error}}
</p>

app.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators, NgForm, FormControl } from '@angular/forms';
import { SearchService } from 'src/app/services/search.service';
import { Subject } from 'rxjs';

@Component({
  ...
  providers: [SearchService]
})

export class AppComponent implements OnInit { 
  results: Object;
  searchTerm$: any = new Subject();
  error: any;

  constructor(private searchService: SearchService) { }

  ngOnit() { }

  getSearchResults(search) {
    this.searchService.search(search).subscribe((res) => {
      console.log(res);
      this.results = res;
    }, err => {
      console.log(err);
      this.error = err.message;
    });
  }
}

search.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { distinctUntilChanged } from 'rxjs/operators';
import { map } from 'rxjs/operators';
import { switchMap } from 'rxjs/operators';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})

export class SearchService {
  public httpOptions = {
    headers: new HttpHeaders({'Content-Type': 'application/json'})
  };

  baseUrl: String = `${environment.API_URL}/api/domainCharts`;
  queryUrl: String = '?search=';

  constructor( private http: HttpClient ) { }

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

  searchEntries(term) {
    return this.http.get(`${this.baseUrl}${this.queryUrl}${term}`);
  }
}

【问题讨论】:

  • 检查是否是使用管道的正确方法..为什么要多次使用管道?
  • RxJS 管道用于将功能运算符组合成一个链。
  • 我已将其更改为 return terms.pipe(debounceTime(500), distinctUntilChanged(), switchMap(term =&gt; this.searchEntries(term))); 但我仍然收到 TypeError: Cannot read property 'pipe' of undefined

标签: angular rxjs


【解决方案1】:

有不止 1 件事与您的要求不符。

首先,您传递了一个Subject 并期待一个Observable。这就是您收到错误的原因

TypeError: 无法读取未定义的属性“管道”

然后,您将Subject 传递为term(我假设您要发送搜索关键字)。

在您的情况下,您不需要Subject。你可以这样做:

模板:

<input type='text' class="form-control input-txt-start" placeholder="Search Domain Name" name="domainId" (keyup)='getSearchResults($event)'>  <---- Send only $event here

组件:

getSearchResults(event) {
    this.searchService.search(event.target.value).subscribe((res) => { // <--- Get target value of event
      console.log(res);
      this.results = res;
    }, err => {
      console.log(err);
      this.error = err.message;
    });
  }
}

服务:

search(term) {  // <--- Notice that the parameter name became term instead of terms

    // You can use of() method of RxJS
    // You need to import of with "import { of } from 'rxjs';"
    // You can chain you operators in pipe() method with commas

    return of(term).pipe(
       debounceTime(500),
       distinctUntilChanged(),
       switchMap(() => this.searchEntries(term) // <--- Notice that, this function has no parameter
     );
  }

【讨论】:

  • 当我按照您的建议进行如下更改时,`search(term) { return terms.pipe(debounceTime(500), distinctUntilChanged(), switchMap(() => this.searchEntries(term) )); `管道不是函数
  • 更新了答案。您可以使用RxJSof() 方法:learnrxjs.io/operators/creation/of.html
  • 但是这样一来,distinctUntilChanged() 变得毫无意义,因为每次触发此函数时都会创建一个新的 observable。我认为您需要将debouncedistinctUntilChanged 移动到组件文件中。也许你可以使用fromEventRxJS 来实现这一点:learnrxjs.io/operators/creation/fromevent.html
  • 非常感谢@Harun,它对我有用。我将尝试通过移动 debounce 和 distinctUntilChanged 并使用 RxJS 的 fromEvent 并让您知道。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
  • 2020-01-17
  • 2021-01-01
相关资源
最近更新 更多