如何在订阅ts angular中具有异步功能

时间:2020-05-25 11:54:43

标签: javascript angular typescript asynchronous

我有一个输入框,在valueChange上调用一个异步函数,该异步函数调用API。

    this.searchFrom = new FormGroup({
      ss: new FormControl()
    });
    this.searchFrom.valueChanges
      .pipe(debounceTime(500))
      .pipe(distinctUntilChanged())
      .subscribe((b) => {
        this.search(b);
      });
  search(ss: string) {
    console.log("? API");
    this.http.post(endpoint + 'search', { 'ss': ss })
      .toPromise()
      .then((data) => {
        this.data = data;
        console.log(data);
        return data;
      })
      .catch((err) => {
        console.error(err);
      })
      .finally(() => {
        console.log("✅✅");
      });
  }

它仅调用函数,不调用.then 在console.log中,我仅得到:

> ? API

2 个答案:

答案 0 :(得分:0)

您应该了解rxjs及其操作符。

这是一个可行的解决方案:

this.searchFrom = new FormGroup({
    ss: new FormControl()
});

this.searchFrom.valueChanges
.pipe(
    debounceTime(500),
    distinctUntilChanged(),
    switchMap(x => this.search(x.ss))
).subscribe((result) => {
    // result contains HTTP-result if non Error
});


search(ss: string) {
    console.log("? API");
    return this.http.post(endpoint + 'search', { 'ss': ss });
}

答案 1 :(得分:0)

不确定为什么将可观察的东西转化为承诺,无论如何,我还有另一种解决问题的方法,

尝试一下

 this.searchFrom.valueChanges.pipe(
            map(value => value.ss),
            debounceTime(500),
            distinctUntilChanged(),
            switchMap(search => this.search(search))
 ).subscribe(data => console.log(data));

 search(ss: string) {
  return this.http.post(endpoint + 'search', { 'ss': ss })
 }