首页 > 解决方案 > 如何从订阅返回数据到 HttpClient

问题描述

我正在实现搜索并尝试使用异步管道和 http 客户端。我应该如何将服务中的 observable 作为定义数组返回?该服务使用 HttpClient 获取一些数据,我需要将其映射到定义列表。安静与rxjs混淆,我应该管道和映射,还是在订阅函数中返回数据或返回observable?

export class DefinitionService {

  constructor(private http: HttpClient) { }

      searchTerm(term: string) {
          return this.http.get('http://localhost:8080/api/search?term=abc')
                  .subscribe((data: string) => {
                    // Data extraction from the HTTP response is already done
                    // Display the result
                    console.log('TJ user data', data);
                  });
      }
    }

在组件中使用 rxjs 运算符处理搜索的代码:

searchInput = new FormControl();

constructor(private definitionService: DefinitionService) {
  this.definitions = this.searchInput.valueChanges
                      .pipe(
                        startWith(''),
                        debounceTime(500),
                        distinctUntilChanged(),
                        switchMap(value => this.definitionService.searchTerm(value))
                      )
}

模板:

<input class="format-input-button"
        (click)="clickInput()"
        [formControl]="searchInput">

<div class="format-options">
  <div *ngFor="let definition of definitions" class="search-result" (click)="selectResult('test result')">
    <div>{{definition.name}}</div>
    <div>{{definition.description}}</div>
  </div>
</div>

我可以做这样的事情吗?

searchTerm(term: string) {
      return this.http.get('http://localhost:8080/api/search?term=abc')
              .pipe(
                map(result => {
                  // do mapping here
                  return mappedData;
                })
              );
  }

有人建议使用异步管道,我应该在搜索结果 Observable 上使用它吗?如果我使用异步管道,我还需要 switchMap 吗?

标签: angularrxjs

解决方案


推荐阅读