2015-11-06 78 views
0

我通過動態構建URL來製作多個GET請求。

對於任何錯誤,我想抓取值response.config.url,處理它,並將結果值推送到一個對象中。

下面的代碼工作正常,當我只有一個錯誤。

當返回多個錯誤時,只有最後一個錯誤的值被推送到對象中。我想那是因爲它會覆蓋前一個(s)。

我該如何預防?如何確保在出現多個錯誤時將所有值都推送到對象中?

(注:annotation是一個字符串我從輸入字段得到的數組; _是lodash)

function checkVariants(annotation) { 
    var lemmas = annotation.text.split(' '); 
    var results = []; 
    var words = []; 
    for (var i = 0; i < lemmas.length; ++i) { 
     var urlLemmas = encodeURIComponent(lemmas[i]).toLowerCase(); 
     results.push(urlLemmas); 
     $http({ 
      method: 'GET', 
      url: 'https://xxxxxxx.org/variants/' + results[i] + '.txt' 
     }).then(function successCallback(response) { 
      console.log('Success: ', response.status) 
     }, function errorCallback(response) { 
      var url = response.config.url; 
      words = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")); 
      _.extend(annotation, { 
       variants: words 
      }); 
     }) 
    } 
} 
+0

你是如何調用多個請求?循環內?什麼是註釋,什麼是你想要的輸出(帶有多個錯誤字符串)? –

回答

2

讓您variants財產的數組,並添加您words到它:

$http({ 
    method: 'GET', 
    url: 'https://wwwcoolservice.org/variants/' + results[i] + '.txt' 
}).then(function successCallback(response) { 
    console.log('Success: ', response.status) 
}, function errorCallback(response) { 
    var url = response.config.url; 
    words = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));     
    if (!annotation.variants || !annotation.variants.length) { // First error: create the array 
     annotation.variants = [words]; 
    } else { // next errors: add to the array 
     annotation.variants.push(words); 
    } 
}); 

有了這個解決方案,您需要檢測您是否已經擁有variants屬性,因此在調用_.extend時會有更多附加值。

+0

我不認爲這是正確的。我得到'annotation.variants.push不是一個函數'。 –

+0

這意味着您的'variants'屬性在第一個錯誤發生之前已經存在於'annotation'對象中。你能告訴你初始化它的位置嗎?與此同時,我調整了代碼以考慮到這一點。如果'variants'屬性不是一個數組,它會被重置爲第一個錯誤字的數組。 – trincot

+0

感謝您的意見,但這不是它應該工作的方式。例如,如果'words'已經有三個值並且我添加了另外一個值,那麼您當前的代碼會將舊的三個值以及新的三個值添加到現有的三個值中!總共有7個值,而不是正確的4. –

0

我設法得到我想要的。

這裏僅供參考代碼:

function checkVariants(annotation) { 
     var lemmas = annotation.text.split(' '); 
     var results = []; 
     var oedVars = []; 
     for (var i = 0; i < lemmas.length; ++i) { 
      var urlLemmas = encodeURIComponent(lemmas[i]).toLowerCase(); 
      results.push(urlLemmas); 
      $http({ 
       method: 'GET', 
       url: 'https://XXXXXX.org/variants/' + results[i] + '.txt' 
      }).then(function successCallback(response) { 
       console.log('Success: ', response.status) 
      }, function errorCallback(response) { 
       var url = response.config.url; 
       var words = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")); 
       oedVars.push(words); 
       _.extend(annotation, { 
        variants: oedVars 
       }); 
      }) 
     } 
    }