Tom
Tom

Reputation: 49

create array of object using interface in angular

I would like to initialize an array with one object inside.

Then, using a function I'd like to be able to push one empty object on it on even later delete one object.

So I have create an interface with the value that are in my object ;

export class Session {
    constructor(
      public genre: string,
      public ordre_interface: number,
      public nb_serie: number
  
    ) {}

    myObject = {} as Session;

}

Then in my main .ts file, I import this interface and initialize my array.

import {Session} from './session.model';

session = [] as Array<Session>;

and I add a function to push a new object inside the array.

addObject() {

    let ses = new Session();
    this.session.push(ses);
}

But first, when I initialize my array session, I like to have one empty object inside like that of I got an empty array [] :

session = [
{
genre: '',
ordre_interface: null,
nb_serie: null,
}
];

And second, inside my function, my code gives me error on line let ses = new Session() :

 Expected 3 arguments, but got 0

I'd like it to create a new object and put it inside the array like that :

session = [
{
genre: '',
ordre_interface: null,
nb_serie: null,
},
{
genre: '',
ordre_interface: null,
nb_serie: null,
}
];

Upvotes: 0

Views: 779

Answers (1)

Talg123
Talg123

Reputation: 1506

export class Session {
    public genre?: string;
    public ordre_interface?: number;
    public nb_serie?: number;
    
    constructor() {}
}

This way you can create a new object with empty data.

Upvotes: 1

Related Questions