Есть некий сервис, отсылает запрос на сервер.
angular
.module('lessonApp')
.service('sendJson', [
'$http',
function($http) {
this.startJson = function (url) {
var startJson={
"operation": "start",
"task": "1"
};
var promise = $http({
url: url,
method: "POST",
data: JSON.stringify(startJson),
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback() {
alert("Ошибка");
});
return promise;
};
}
]);
Вот его вызываем и после ответа выводим все успешно:
sendJson.startJson(url).then(function (response) {
alert('Запрос вернул ответ');
});
Но нужно изменить код, после успешного ответа от сервера нужно посылать другой запрос на сервер периодически до того времени пока не придет нужный ответ. То есть запрос должен повторятся и когда придет нужный ответ уже возвращать это. Например
var promise = $http({
url: url,
method: "POST",
data: JSON.stringify(startJson),
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}
}).then(function successCallback(response) {
console.log(response.data);
//???
var resultJS={
"operation": "result",
"task": "1"
};
var resultExist=false;
while (resultExist==false) {
var promiseResult = $http({
url: url,
method: "POST",
data: JSON.stringify(resultJS),
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}
}).then(function successCallback(responseResult) {
if(responseResult.data.status=='done')
resultExist=true;
},function errorCallback() {
alert("resultJS error");
});
return promiseResult;
}
//???
}, function errorCallback() {
alert("Ошибка");
});
return promise;
Вынес вложенный запрос в отдельный файл-сервис, если первый запрос успешный исполняем второй
angular
.module('lessonApp')
.service('resultJson', [
'$http',
function($http) {
this.getResultJson = function (url) {
var resultJson={
"operation": "result",
"task": "1",
};
var promise = $http({
url: url,
method: "POST",
data: JSON.stringify(resultJson),
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}
}).then(function successCallback(response) {
if(response.data.status=='in proccess'){
self.getResultJson(url); //подправил
}else{ return 'done';}
}, function errorCallback() {
alert("Ошибка");
});
return promise;
};
}
]);
Рекурсия кажется работает, но как правильно возвращать promise
?
Content-Type: application/x-www-form-urlencoded
? У JSON медиа-тип совсем другой,application/json
.