Bailey Miller
Bailey Miller

Reputation: 1

Return data from service not returning proper data

I wrote an Angular service that gets some fake data from my C# backend. The C# backend is using an ASMX file for the process. I have data coming back and everything is all nice and then my data never populates.

I have this feeling it has something to do with the data pass off coming back from the promise.

Service:

app.service('fakeDataCenter', function ($http) {
    this.getFakeData = function ()
    {
        var obj = {
            phoneNumber: "",
            faxNumber: "",
            address: "Loading..",
            };
        $.ajax({
            type: "POST",
            url: "/Services/DataService.asmx/getFakeData",
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: "json",
            success: function(data, status){
                obj = data;
            }
        });

        return obj;
    };});

I can tell that I hit return obj, before I hit the line obj = data. How do I make the code return only after data has been populated.

I have already tried putting the return statement inside the success function without any luck. It just returns an undefined object.

Upvotes: 0

Views: 123

Answers (1)

lealceldeiro
lealceldeiro

Reputation: 14978

I recommend you to use the angular approach, since you are using angular in your app. Change your service method like this:

this.getFakeData = function (){
   var obj = {
            phoneNumber: "",
            faxNumber: "",
            address: "Loading..",
            };
    return $http.post('/Services/DataService.asmx/getFakeData', obj).then(
          function (res){
             return res.data;
          },
          function(onErr){
             return onErr.data;
          }
    )
}

and then in your angular controller you can get the returned data like this:

fakeDataCenter.getFakeData().then(
    function(data){
        //here in data there is your C# backend service data
    }
);

Upvotes: 1

Related Questions