繁体   English   中英

如何在订阅 ts angular 内有异步 function

[英]How to have async function inside subscribe ts angular

我有一个输入框,在 valueChange 上调用一个异步 function,它调用 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("✅✅");
      });
  }

它只是调用 function,它不调用.then在 console.log 我只得到:

> 📡 API

您应该了解 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 });
}

不知道你为什么要把你的 observable 转换成 promise,反正我有另一种方法来解决你的问题,

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM