0

How can I get value with angular / typescript in this table ..

My console log

How can I get the value of code and label .. I tried to do this code but it's not worked :

MyComponent.ts

  jsonsTypes = []; // define here global variable
    saveFolder() {
        let tab = [];
         this.adminService.getLabelByCode(code).subscribe(
          labelByCode => {
            tab.push({
              'code': code,
              'label': labelByCode.label
            });
          });
           this.jsonTypes.push(tab);
          //here when I do console.log(tab); ==> I have the result of the picture
        for (var index = 0; index < this.jsonTypes.length; index++) {
            console.log(jsonTypes[index]); 
            console.log(jsonTypes[index].code); // ==> undefined            
            // How can I get value ?
        }
    }   
user1814879
  • 984
  • 6
  • 23
  • 49
  • 2
    Do the for inside subscribe, because the value is assigned once getLabelByCode(code) finished. You are doing the for loop outside this and therefore, it loops through an empty array. – trungk18 Aug 17 '17 at 13:34
  • Your subscribe-method doesn't really fit in there. the subscription should be done once. – Christian Aug 17 '17 at 13:35
  • I do mistake in my first post -- I edit it – user1814879 Aug 17 '17 at 13:51
  • Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – AT82 Aug 19 '17 at 09:58

1 Answers1

0

This will result the code:

console.log(jsonTypes[index][0].code);

But the problem is, that you don't need to make "tab" to an array.

Try this... It's not tested, but should work.

jsonsTypes = []; // define here global variable
saveFolder() {
  this.adminService.getLabelByCode(code).subscribe(
    labelByCode => {
     this.jsonTypes.push({
        'code': code,
        'label': labelByCode.label
      });
    });

  for (var index = 0; index < this.jsonTypes.length; index++) {
    console.log(jsonTypes[index]); 
    console.log(jsonTypes[index].code);
  }
}   
iCodr8
  • 160
  • 1
  • 5