首页 > 解决方案 > Angular:过滤器更改后获得结果的正确方法

问题描述

在我的简单应用程序中,我有 FilterComponent、ListComponent 和一项服务(我称之为 GithubService)。

我需要通过 http 到 github 输入 FilterComponent 地址中的搜索词并将结果返回给 ListComponent。

export class GithubService {
  baseUrlSearch ="https://api.github.com/search";       

 initResponse:IResponse = {total_count:0,incomplete_results:false,items:[]}

    //subject = new Subject<IResponse>();
    subject = new BehaviorSubject<IResponse>(this.initResponse);

   constructor(private http: HttpClient) {  }


public setSearch(newSearchText:string):void{
  if (newSearchText.length<=3) return;
  const url=`${this.baseUrlSearch}/users?q=${newSearchText}`;
  this.http.get<IResponse>(url).pipe(debounceTime(500)).subscribe(
    res=> this.subject.next(res));      
}
public getResults():Observable<IResponse>
{
 return  this.subject.asObservable();
}

// ListComponent class
export class ListComponent implements OnInit {

  response$: Observable<IResponse>;
  constructor (private service :GithubService)
  {}
  ngOnInit(): void {
    this.response$= this.service.getResults();
  }
}

我不知道每次更改 newSearchText 时服务都会订阅。

我应该保持不动还是以某种方式重构,或者每次都取消订阅?

标签: angulartypescriptsubject-observer

解决方案


推荐阅读