2015-01-22 2 views
0

Для моего сайта я делаю http-запрос для доступа к API. Он запускается при нажатии клавиши. Проблема в том, что он вызывает много вызовов ajax при каждом непрерывном нажатии клавиши, поэтому для управления этим я должен добавить небольшой тайм-аут, например, 300 мс. Я сделал http-вызов следующим образом, как я могу изменить это сейчас?Ждите выполнения запроса HTTP AngularJS

var req = { 
    method: 'GET', 
    url: 'url of api', 
    headers: { 
     "Key": "keyofapi", 
     "Accept": "application/json" 
    }, 
}; 

$http(req) 
    .success(function(data, status, headers, config) { 
    }) 
    .error(function(data, status, headers, config) { 
    }); 
+0

Что именно вы спрашиваете? Ваш вопрос непонятен. – Jan

+0

@Jan Я хочу добавить задержку при выполнении запросов, проверьте эту ссылку http://s6.postimg.org/bw2uuera9/svo.png – droidev

+0

, вы можете отключить функцию if, –

ответ

1

Оберните функции внутри функции $ таймаута, говоря таймаут (P.S он принимает значение в мс). Не забудьте ввести $ timeout в параметры вашего контроллера. Попробуйте это,

$timeout(function() { 
     $http({ 
       method: 'POST', //No I18N 
       url: 'your URL', //No I18N 
       params: { 
        parameters if needed 
       } 
      }).success(function (data, status, headers, config) { 
       //Do the required 
      }); 
     }, 2500); 
1

Я действительно рекомендую сделать завод или услугу, которые смотрят, если у вас есть активный запрос, и вы ждали этого.

yourApp.factory('apiReqeust', ['$http', function($http) { 
    // If you want to complete all requests that you sending, 
    // make this varable an empty array and push every new request inside it. 
    var waitingRequest = null; // Or quenuedRequests = []; 
    var isWorking = false; 
    // In my case I will not make an array, and will have only one request that will wait. 
    // I mean the last attempted request. 
    // This is perfect for an Autocomplete API 

    function request(options, callback) { 
    if (isWorking) { 
     // If you are already running request at this time. 
     // Replace waiting request with this one. (this one is newer request) 
     waitingRequest = {options: options, callback: callback} 
     // EDIT! I forgot about the return statement. 
     // You need to stop, otherwise the request will be executed anyway. 
     return; 
    } 
    isWorking = true; 

    $http(options).success(function(data) { 
     // When the request ends, tell that you are not working 
     // So you can execute next request immediately 
     isWorking = false; 

     // execute callback with data parameter. 
     callback(data); 

     // If you have waiting request yet. execute it. 
     if (waitingRequest) { 
     request(waitingRequest.options, waitingRequest.callback); 

     waitingRequest = null; 
     } 
    }).error(function(err) { 
     isWorking = false; 
     callback(null, err); 
     if (waitingRequest) { 
     request(waitingRequest.options, waitingRequest.callback); 
     } 
    }); 
    } 
    return request; 
}); 

Использование этого:

// Factory or controller or whatever that can depend on above factory 
youApp.factory('another-whatever', ['apiRequest', function(apiRequest) { 
    options = {'Some': 'HttpOptions'}; 
    apiRequest(options, function(data, err) { 
    if (err) throw new Error(err); 
    // And here you doing what you want with the data. 
    }); 
}]); 

Я не проверял этот код. Я не знаю, работает ли это. Но я надеюсь, что у вас есть идея.

+0

См. мои изменения в комментариях. Я забыл инструкцию 'return' в строке 17. – Ifch0o1

1

На самом деле я рекомендую сделать завод или услугу, если у вас есть активный запрос, и вы его ждали.

function request(options, callback) { 
    if (isWorking) { 
     // If you are already running request at this time. 
     // Replace waiting request with this one. (this one is newer request) 
     waitingRequest = {options: options, callback: callback} 
     // EDIT! I forgot about the return statement. 
     // You need to stop, otherwise the request will be executed anyway. 
     return; 
    } 
    isWorking = true; 

    $http(options).success(function(data) { 
     // When the request ends, tell that you are not working 
     // So you can execute next request immediately 
     isWorking = false; 

     // execute callback with data parameter. 
     callback(data); 

     // If you have waiting request yet. execute it. 
     if (waitingRequest) { 
     request(waitingRequest.options, waitingRequest.callback); 

     waitingRequest = null; 
     } 
    }).error(function(err) { 
     isWorking = false; 
     callback(null, err); 
     if (waitingRequest) { 
     request(waitingRequest.options, waitingRequest.callback); 
     } 
    }); 
    } 
    return request; 
}); 

Использование этого:

// Factory or controller or whatever that can depend on above factory 
youApp.factory('another-whatever', ['apiRequest', function(apiRequest) { 
    options = {'Some': 'HttpOptions'}; 
    apiRequest(options, function(data, err) { 
    if (err) throw new Error(err); 
    // And here you doing what you want with the data. 
    }); 
}]); 
Смежные вопросы