[英]How can I ensure a minimum input length with rxjs filter
I am trying to use the filter property on a Angular formcontrol.我正在尝试在 Angular 表单控件上使用 filter 属性。
This is the code:这是代码:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { SpotifyService } from '../services/spotify.service';
import { Artist } from '../models/models';
import { Observable, Subscription } from 'rxjs/Rx';
@Component({
selector: 'spt-search',
templateUrl: './search.component.html',
styles: []
})
export class SearchComponent implements OnInit {
public searchResult: Observable<Array<Artist>>;
public searchString: string;
public term = new FormControl;
constructor(private spotService: SpotifyService) { }
ngOnInit() {
this.searchResult = this.term.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.filter((query: string) => query.length > 1)
.switchMap(term => this.spotService.searchMusic(this.term.value).map(res => res.artists.items));
}
}
When I try to set a filter I get this error:当我尝试设置过滤器时,出现此错误:
EXCEPTION: Uncaught (in promise): Error: Error in :0:0 caused by: this.term.valueChanges.debounceTime(...).distinctUntilChanged(...).filter is not a function
TypeError: this.term.valueChanges.debounceTime(...).distinctUntilChanged(...).filter is not a function
at SearchComponent.ngOnInit (http://localhost:4200/main.bundle.js:229:14)
at Wrapper_SearchComponent.ngDoCheck (/AppModule/SearchComponent/wrapper.ngfactory.js:22:53)
at CompiledTemplate.proxyViewClass.View_SearchComponent_Host0.detectChangesInternal (/AppModule/SearchComponent/host.ngfactory.js:28:29)
at CompiledTemplate.proxyViewClass.AppView.detectChanges
Hi i think your problem is that the function .distinctUntilChanged()
doesn't return a collection on which you can attach the .filter()
method ..but you can give a try to this:嗨,我认为您的问题是函数
.distinctUntilChanged()
没有返回一个集合,您可以在其上附加.filter()
方法.filter()
但是您可以尝试一下:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { SpotifyService } from '../services/spotify.service';
import { Artist } from '../models/models';
import { Observable, Subscription } from 'rxjs/Rx';
@Component({
selector: 'spt-search',
templateUrl: './search.component.html',
styles: []
})
export class SearchComponent implements OnInit {
public searchResult: Observable<Array<Artist>>;
public searchString: string;
public term = new FormControl;
constructor(private spotService: SpotifyService) { }
ngOnInit() {
this.searchResult = this.term.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.filter((query: string) => query && query.length > 1 ? query.length > 1 : "")
.switchMap(term => this.spotService.searchMusic(this.term.value).map(res => res.artists.items));
}
}
or maybe you can also null propagation like:或者你也可以空传播,如:
.filter((query: string) => query?.length > 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.