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

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

在字段中輸入3個字符后如何執行API調用?

在字段中輸入3個字符后如何執行API調用?

明月笑刀無情 2022-12-22 14:39:58
我正在使用父子組件。子組件有輸入字段,并將用戶輸入的值發送給父組件,如下所示:<parent-component (sendInputValue)="getInputValue($event)"><parent-component>現在在父組件中我有這個:getInputField(data){ console.log(data); // this prints the data (Example: abc) //  then here I'm just executing the API call ONLY if data length is 3  if(data.length === 3){    this.myService.getDataFromService(data).subscribe(rs=>console.log(rs));  }}現在假設發生這種情況:用戶輸入:abc // API 調用得到執行,這很好現在,用戶輸入:abcd // 沒有 API 調用被執行,這很好現在用戶刪除字母“d”,數據的新值將是“abc”我不想再次執行 API 調用,因為我們已經執行了“abc”的 API 調用現在,如果用戶刪除字母“c”,數據的新值現在是“ab”。此時,預計不會有 API 調用現在,如果用戶添加字母“c”,新值將是“abc”。此時,API 調用是預期的。(這是有效的)那么,如果輸入數據是 3 個字符,并且如果用戶輸入更多字符,則如何始終執行 API 調用,如果用戶刪除字符并返回到前 3 個字符,則不應發生任何事情,因為 API 已經發生了?非常感謝!
查看完整描述

6 回答

?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

我認為您需要distinctUntilChanged 并且可以在管道中使用過濾器

this.myService.getDataFromService(data)

  .pipe(

    filter(_ => data.length === 3), 

    distinctUntilChanged()

  ).subscribe(rs => console.log(rs));


查看完整回答
反對 回復 2022-12-22
?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

下面是您的代碼中的小調整,它將滿足您告訴的要求。


您絕對可以使用 debounce、distinctUntilChanged、switchMap 運算符改進此過程。


previousData = '' // create a property which will track of previous data from parent component.


getInputField(data){

  if(data && data.length === 3 && data.length > previousData.length){

    this.myService.getDataFromService(data).subscribe(rs=>console.log(rs));

  }

  this.previousData = data || ''; // update previous data to current data after backend call.

}


查看完整回答
反對 回復 2022-12-22
?
翻閱古今

TA貢獻1780條經驗 獲得超5個贊

使用RxJs FromEvent方法從input字段中監聽輸入事件。


@ViewChild('#input', {static:true}) inputField: ElementRef<any>;


ngOnInit(){

   FromEvent(inputField, 'input')

     .pipe(

         map(event => event.target.value),

         map((value:string) => value.trim()),

         filter((value:string) => value.length === 3), 

         debounceTime(500),

         distinctUntilChanged()

     )

     .subscribe(keyword => {

         // API Call(keyword)

     })

}


查看完整回答
反對 回復 2022-12-22
?
暮色呼如

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

我制作了一個通用函數,您可以將它用于任意數量的字符以限制您的 API 調用。


const cached = {};

/**

 * @desc Check if API call is allowed or not 

 * based on provided input and length condition

 * @param {String} input - input value

 * @param {Number} len   - length of the input over which API has to be called.

 * @returns {Boolean}

 */

function doCallAPI(input, len) {

  if(input.length === len) {

    if(!cached[input]) {

      // Call the API

      cached[input] = 1;

      return true;

    }

  }

  else if(input.length < len) for(let i in cached) cached[i] = 0;

  return false

}

解釋:

  1. 檢查輸入的長度是否等于條件長度(此處為 3)。

    • 如果否,則不會為此輸入值調用 API?,F在,

    • SET cached[input value] = 1,在緩存對象中插入值。

    • 如果是,則檢查緩存的對象是否具有具有輸入值的鍵并且它具有值(例如 1)

    • 返回 true,表示允許調用 API。

  2. 檢查輸入的長度 (Say, 2) 是否小于條件長度。

  3. 然后,遍歷緩存對象并將所有內容設置為 0,以告知現在允許對條件長度的緩存值進行 API 調用(此處為 3)。

  4. 返回 false,告訴 API 調用是不允許的。

這是如何使用它,

getInputField(data){

 console.log(data); // this prints the data (Example: abc)

 //  then here I'm just executing the API call ONLY if data length is 3

  if(doCallAPI(data, 3)){

    this.myService.getDataFromService(data).subscribe(rs=>console.log(rs));

  }

}


查看完整回答
反對 回復 2022-12-22
?
翻翻過去那場雪

TA貢獻2065條經驗 獲得超14個贊

 private lastLetter = "";


    getInputField(data) {

     if(!this.lastLetter === data.toLowerCase()) && data.length === 3) {

        this.myService.getDataFromService(data).subscribe(rs=>{

        this.lastLetter = data.toLowerCase();

        console.log(rs)

        });

      }

    }

我想這行得通


查看完整回答
反對 回復 2022-12-22
?
婷婷同學_

TA貢獻1844條經驗 獲得超8個贊

首先,讓我們讓您的輸入數據可觀察 - 以便更容易實現其他一切:


private inputData$ = new Subject<string>();


public getInputField(data: string){

  this.inputData$.next(data);

}

現在我們可以用這個輸入流做任何我們想做的事。例如,采用上面@Thorsten Rintelen 建議的方法


ngOnInit() {

  this.inputData$

    .pipe(

      filter(data => data.length === 3),

      distinctUntilChanged(), // this makes sure api call is sent only if input has changed

      switchMap(data => this.myService.getDataFromService(data)),

    )

    .subscribe(apiResult => console.log(apiResult));

}

注意: 這種方法只緩存最后的輸入。如果您想緩存和重用所有 api 響應,您可以將 api 服務方法包裝到某個緩存層中,而無需更改任何其他內容。


查看完整回答
反對 回復 2022-12-22
  • 6 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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