2

I am trying to wait for the server to return the some data and then do another callback. This is my code

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;
}
]);

I am calling this factory method as below

scope.sendReply = function () {
     updateModel();
     var replyModelValue = scope.replyModel;
     replyMessageFactory.send(scope.replyModel).then(function (data) {
             scope.clear();
             scope.updateThread(replyModelValue);
     });
}

The thing is that I am not getting the latest data from the back end. If I add timeout then it works. Could it also be because of the back end?

My backend api is this

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;
    }
}

Any ideas?

mohsinali1317
  • 4,255
  • 9
  • 46
  • 85

1 Answers1

2

You should not pass that scope.updateThread into the factory, instead you should only return the $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;
  }
]);

And you will call it like:

scope.sendReply = function () {
    replyMessageFactory.send(scope.replyModel)
        .then(function (result) {
            scope.updateThread(result);
        });
}

Now your scope.updateThread can work syncronously.


P.S. care about that typo into scope.updateThread parameter, it should be:

scope.updateThread = function (obj) {
    getMessages.getMessageById(obj, scope.updateThreadCallback);
}
Fabio Ruggiero
  • 309
  • 2
  • 7