我正在尝试等待服务器返回一些数据,然后进行另一个回调。这是我的代码
commonApp.factory('replyMessageFactory', ['$q', '$http', '$log', function ($q, $http, $log) {
var factoryObj = {};
factoryObj.send = function (obj) {
var req = {
method: 'POST',
url: "/api/ThreadMessage",
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: obj
}
return $http(req);
}
return factoryObj;
}
]);
我调用这个工厂方法如下
scope.sendReply = function () {
updateModel();
var replyModelValue = scope.replyModel;
replyMessageFactory.send(scope.replyModel).then(function (data) {
scope.clear();
scope.updateThread(replyModelValue);
});
}
问题是我没有从后端获取最新数据。如果我添加超时,那么它就会起作用。难道也是后端的原因?
我的后端API是这样的
public async Task<HttpResponseMessage> Post(ThreadMessageModel messageData)
{
try
{
await _findMessageService.AddMessageReply(findmessage);
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (Exception exception)
{
Log.Log(EventSeverity.Error, new { Message = "Could not create message", exception });
throw new Exception(string.Format("Kan ikke opprette melding. {0}", exception));
}
}
public Task<int> AddMessageReply(FindMessage message)
{
try
{
client.Update<FindMessage>(message.Id).Field(x => x.Replies, message.Replies).Execute();
return Task.FromResult(1);
}
catch (Exception exception)
{
log.Log(EventSeverity.Error, "Could not add message and feedback status", exception);
throw;
}
}
有什么想法吗?
最佳答案
您不应该将 scope.updateThread
传递到工厂中,而应该只返回 $http Promise。
commonApp.factory('replyMessageFactory', ['$q', '$http', '$log', function ($q, $http, $log) {
var factoryObj = {};
factoryObj.send = function (obj) {
var req = {
method: 'POST',
url: "/api/ThreadMessage",
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: obj
};
return $http(req);
}
return factoryObj;
}
]);
你会这样调用它:
scope.sendReply = function () {
replyMessageFactory.send(scope.replyModel)
.then(function (result) {
scope.updateThread(result);
});
}
现在您的 scope.updateThread
可以同步工作了。
附注关心 scope.updateThread
参数中的拼写错误,它应该是:
scope.updateThread = function (obj) {
getMessages.getMessageById(obj, scope.updateThreadCallback);
}
关于javascript - 如何在 Angular 中使用 Promise 并摆脱超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50252879/