角度:父组件中子组件的valueChanges使用switchmap

时间:2019-03-27 09:42:42

标签: angular

我有孩子SearchComponent向父ErrorsListComponent组件发送搜索文本。 父组件将其发送到ErrorsGettingService服务,该服务发出结果并将其传递回ErrorsListComponent

但是,如果我在SearchComponent内的输入中快速键入多个字母,则会在ErrorsListComponent中得到跳转结果。在父组件的valueChanges内部的输入中,我需要switchMapSearchComponent之类的东西,但我不知道该如何实现。

export class ErrorsListComponent  {
  p:number;
  itemsPerPage:number= 50;
  errorLogs$:Observable<IErrorLog[]>; 

  constructor (private service :ErrorsGettingService)
  {    
    this.errorLogs$=this.service.getResults();    
  }

  public  doSearch(searchVal:string):void
  {
    this.service.setSearch(searchVal);
  }
}

export class ErrorsGettingService {

  initResponse:IErrorLog[] = null;
  subject = new BehaviorSubject<IErrorLog[] >(this.initResponse);

  _baseUrl:string;
  constructor(private http: HttpClient,
    @Inject(TERMINAL_URL) terminalUrl: string) { 
      this._baseUrl = terminalUrl;          
      this.setSearch(null);
     }    

public setSearch(newSearchText:string):void{  
  this.subject.next(null);
  let url=`${this._baseUrl}api/errors`;

  if (newSearchText!=null && newSearchText.length>0) 
   url=`${this._baseUrl}api/errors?filter=${newSearchText}`;

 this.http.get<IErrorLog[]>(url).pipe(   
   debounceTime(300)).toPromise().then(res=>{  
   this.subject.next(res);
  })
 /* .subscribe(
    res=> { this.subject.next(res); subscription.unsubscribe();}); */ 
}

public getResults():Observable<IErrorLog[]>
{
 return  this.subject.asObservable();
}}

1 个答案:

答案 0 :(得分:1)

ErrorsGettingService中创建主题,并在每次获取新值时为其添加值。

let parentSubject: Subject<string> = new Subject<string>()

setSearch()

parentSubject.next(searchString);

parentSubject.pipe((switchMap(() => {
    return this.http.get<IErrorLog[]>(url).pipe(   
        // debounceTime(300)).toPromise().then(res=>{  
        // this.subject.next(res);
    })
}))).subscribe(() => {
    // rest of your code
})

每当将新值添加到parentSubject时,您之前的“ HTTP”请求都将被取消,您也可以使用debounceTime()来取消此请求