5

I have an array called rows of type TestEvent, and want to push to the array, i cant get to output the object i pushes it only shows undefined As you can see this.rows shows the arrays, but when i try to output a spesific array this.rows[0] i get undefined. (Typescript 2.7, Angular 5)

I've tried the following guides:


import { TestEvent } from '../../models/event'
rows: TestEvent[] = []

public push(){
    var test: TestEvent = {id: '222', category:'testcat', event_name: 'name'}
    console.log(test) // Outputs the array

    this.rows.push(test)    //Push the array to this.rows

    console.log(this.rows)  //Outputs array of objects
    consloe.log(this.rows[0])   //Outputs undefined
}

Event.ts

export interface TestEvent{
    id?: string,
    category?: string,
    event_name?: string
}
Igor
  • 55,253
  • 10
  • 80
  • 149
Vlad J
  • 95
  • 1
  • 6
  • Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Igor Mar 08 '18 at 13:50
  • Start by writing code that is formatted and can transpile. Then look at the marked duplicate, you are using `this` when you should not be as `rows` seems to be a local variable. – Igor Mar 08 '18 at 13:51
  • i've forgot to mention that the push was run inside a method – Vlad J Mar 08 '18 at 13:55
  • That could definitely affect `this` depending on how the method was called. `this` could be associated with the browser window object. – Igor Mar 08 '18 at 13:56

1 Answers1

7

That code has no problem and I tested on my local(typescript : 2.5 , angular5). And I got "row[0] : {id: "222", category: "testcat", event_name: "name"}"

interface TestEvent{ 
id?: string,
  category?: string,
  event_name?: string
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  rows: TestEvent[] = [];

  ngOnInit(){
    var test: TestEvent = {id: '222', category:'testcat', event_name: 'name'};
    console.log(test); // Outputs the array

    this.rows.push(test); //Push the array to this.rows

    console.log(this.rows); //=> 0:{id: "222", category: "testcat", event_name: "name"}
    console.log(this.rows[0]); // => {id: "222", category: "testcat",event_name: "name"}

    }
}
Jihoon Kwon
  • 690
  • 5
  • 12