3

I have the following Typescript class, with it's Click function, which is triggered by a button click, in my mobile app. The bit of interest is the todoItemTable.read, which goes and gets an array of ToDoItems from my cloud backend. The current code works and spits out the text of 8 todo items, but I want to store the text in an array, so if you see the commented out line where I push into todos, that was how I thought I woula pproach the issue. However, that line of code stos the loop running, so I get the first ToDo item logged twice and then nothing else. The application does't hang and there is no error.

export class HelloWorldModel extends Observable {
  public todos: any[]; 

  constructor() {
    super();
  }

  Click() {
    var client = new MobileServiceClient("https://example.azurewebsites.net");
    console.log("CLIENT");
    var todoItemTable = client.getTable("TodoItem");
    console.log("Table");
    this.todos = [];
    todoItemTable.read<TodoItem>().then(function (results) {
      // results is array of TodoItem-s
      console.log(results.length);
      console.log(results[0].text);
      for (let i of results) {
        console.log(i.text);
        //this.todos.push(i.text);
      }
    });
  }

}

What is going wrong?

2 Answers 2

5

To work with the same scope use arrow functions, like this:

todoItemTable.read<TodoItem>().then((results) => {
  for (let i of results) {
    this.todos.push(i.text);
  }
});

See the Mozilla Developer Network on Arrow functions

Sign up to request clarification or add additional context in comments.

Comments

0

I was having this same problem, whenever I tried using array.push() anywhere in my loop it would run through once and then stop. I fixed this problem by instantiating the array as an empty array (array: string[ ] = [ ]) OUTSIDE of my loop. then instantiating the new string to be pushed to the array INSIDE the loop. hope this helps anyone out there =)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.