如何从订阅返回数据到HttpClient

时间:2019-08-13 10:58:27

标签: angular rxjs

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

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;
                })
              );
  }

有人建议使用异步管道,我应该在搜索结果“可观察”中使用它吗?如果我使用异步管道,是否还需要switchMap?

0 个答案:

没有答案