Undefined property of a typed Array (Typescript)?

I've been struggling with a simple problem (but it's already givin' me a headache). I have the code below:

interface IFoo{
   ReturnFirstBarObject1(): string;
   FillBarArray(array: Array<Bar>): void;
}

class Bar {
  object1: string;
  object2: string;
}

class Foo implements IFoo{
  array: Array<Bar>;

  constructor(){
    this.array = new Array<Bar>();
  }

  public ReturnFirstBarObject1(): string {
     return this.array[0].object1;
  }

  public FillBarArray(array: Array<Bar>): void {
     this.array = array;
  }
}

$(document).ready(function(){
  var foo = new Foo();

  $.get('url/getBars?FooID=1')
   .done(function(data: any){
       foo.FillBarArray(data);
   });

  var object1 = foo.ReturnFirstBarObject1();
});

I don't know why but object1 returns for me as 'undefined' and when I highlight 'this.array[0]' it returns a JSon like this

"{'object1' : 'someString', 'object2' : 'someString'}"

I want to access object1 but it returns undefined and I can't do a workaround on the Json because typescript recognize the array object as a Bar.

Anyone knows why this is happening and what can I do to access Bar property properly ?

Upvotes: 0

Views: 1101

Answers (2)

Madhu Ranjan
Madhu Ranjan

Reputation: 17894

It seems you are trying to get the first element before you have filled the array,

below code executes before your ajax calls fills the array, hence you are getting undefined error.

var object1 = foo.ReturnFirstBarObject1();

If you move this code inside ajax call it should work,

$.get('url/getBars?FooID=1')
  .done(function(data: Array<Bar>){
     foo.FillBarArray(data);
     var object1 = foo.ReturnFirstBarObject1();
});

Upvotes: 1

fips
fips

Reputation: 4379

The result here is a json string not a json object. Try $.getJSON.

Also @Madhu Ranjan's answer about jquery's callback possibly returning after the call to ReturnFirstBarObject1 is another thing to consider that could cause this problem.

Upvotes: 0

Related Questions