类型化数组(Typescript)的未定义属性?

时间:2016-05-16 00:27:32

标签: typescript

我一直在努力解决一个简单的问题(但它已经给我带来了麻烦)。 我有以下代码:

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

我不知道为什么但是object1以“undefined”的形式返回给我,当我突出显示'this.array [0]'时它返回一个像这样的JSon

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

我想访问object1,但它返回undefined,我无法对Json进行解决,因为typescript将数组对象识别为Bar。

任何人都知道为什么会这样,我该怎么做才能正确访问Bar属性?

2 个答案:

答案 0 :(得分:1)

在填写array

之前,您似乎正在尝试获取第一个元素

下面的代码在你的ajax调用填充数组之前执行,因此你得到了未定义的错误。

var object1 = foo.ReturnFirstBarObject1();

如果你在ajax调用中移动此代码,它应该可以工作,

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

希望这会有所帮助!!

答案 1 :(得分:0)

这里的结果是json字符串而不是json对象。试试 /// <summary> /// Run Async /// </summary> /// <typeparam name="T">The type to return</typeparam> /// <param name="Code">The callback to the code</param> /// <param name="Error">The handled and logged exception if one occurs</param> /// <returns>The type expected as a competed task</returns> public async static Task<T> RunAsync<T>(Func<string,T> Code, Action<Exception> Error) { var done = await Task<T>.Run(() => { T result = default(T); try { result = Code("Code Here"); } catch (Exception ex) { Console.WriteLine("Unhandled Exception: " + ex.Message); Console.WriteLine(ex.StackTrace); Error(ex); } return result; }); return done; } public async void HowToUse() { //We now inject the type we want the async routine to return! var result = await RunAsync<bool>((code) => { //write code here, all exceptions are logged via the wrapped try catch. //return what is needed return someBoolValue; }, error => { //exceptions are already handled but are sent back here for further processing }); if (result) { //we can now process the result because the code above awaited for the completion before //moving to this statement } }

同样@Madhu Ranjan关于jquery的回调可能会在调用$.getJSON之后返回,这是另一件可能导致此问题的事情。