Reputation: 95
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
}
Upvotes: 5
Views: 19036
Reputation: 126
Try this one.
TestEvent.ts
import { Event } from "./Events";
class EventClass{
Events:Event[]=[];
constructor()
{
}
pushElement(Event:Event)
{
this.Events.push(Event) // Push Event parameter value to the Events array
console.log(this.Events) // Output [{{id:"1",category:"Corporate Event",event_name:"Corporatiz Fair"}}]
}
}
var event=new EventClass()
event.pushElement({id:"1",category:"Corporate Event",event_name:"Corporatiz Fair"}); //calling pushElement method of EventClass
Event.ts
export interface Event{
id:string,
category:string,
event_name:string
}
Upvotes: 2
Reputation: 1
There is a simple way to bypass that issue. You just use the array length property and assign the new TestEvent values to the end of the array
var test: TestEvent = {id: '222', category:'testcat', event_name: 'name'}
console.log(test); // Outputs the array
this.rows[this.rows.length] = test; //adds the array to this.rows as the last element
console.log(this.rows); //Outputs array of objects
Upvotes: 0
Reputation: 755
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"}
}
}
Upvotes: 9