亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在訂閱 ts angular 內部具有異步函數

如何在訂閱 ts angular 內部具有異步函數

慕的地8271018 2022-09-02 20:54:47
我有一個輸入框,它在 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("??");      });  }它只是調用函數,它不調用控制臺.log我只得到:.then> ?? API
查看完整描述

2 回答

?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

您應該了解 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 });

}


查看完整回答
反對 回復 2022-09-02
?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

不知道為什么你要把你的可觀察性轉化為承諾,無論如何,我有另一種方法可以解決你的問題,


試試這個


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

 }


查看完整回答
反對 回復 2022-09-02
  • 2 回答
  • 0 關注
  • 99 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號