Krishan
Krishan

Reputation: 2487

TypeScript with Angular.JS and web API

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?

Upvotes: 0

Views: 2262

Answers (1)

basarat
basarat

Reputation: 276255

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.

Upvotes: 2

Related Questions