Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm working on an asp.mvc3 web api project. in this project I use TypeScript and Angular.js and I need to access the business layer from TypeScript through the Web API. I called the Web API inside the constructor method in TypeScript using the code given below.

constructor($scope, $http: any) {
    $scope.VM = this;
    $http.get("/API/PrivateAPI/Test/1").success((a) => { this.Tiles = a });
    var bb = this.Tiles;
}

However, when trying to get the object list from the business layer, the Tiles array is empty. I debugged the code and found out the Web API is called after passing the last line of the constructor and does return results. I need to call that method inside the constructor and get object list to the Tiles array.

Does anyone know how to do so?

share|improve this question
Does this typescript (a) => translate into function(a)? because that's what success will be expecting (a function with an argument that it will pass the resolved data to) – shaunhusain yesterday

1 Answer

First of, I think you should do the following (notice .data) :

$http.get("/API/PrivateAPI/Test/1").success((response) => { this.Tiles = response.data });

Anyways, $http only supports async http requests. What you want can be done by a synchronous XHR request and that is considered bad UI experience, since the browser window freezes till the XHR request completes, and therefore $http doesn't support it (configuration docs).

What you can do is something like :

  1. call another function from response e.g.

    (response) => { this.Tiles = response.data; this.continueWithProcessing(); }
    
  2. Or, Setup a variable to hide a preloader when the response comes back:

    (response) => { this.Tiles = response.data; this.allDone=true; }
    

    Where you have an ng-show on something like:

    <div ng-show="!VM.allDone">Loading the data....</div> 
    

Or both :)

Note: An async setting is supported in underlying browsers native XHR object and therefore in $.ajax which is the jquery ajax function : http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings. However it is a horrible UI experience + if you use it from angular you are responsible for scope.apply.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.