Import an instance of a class into an Angular component

Discussão em 'Angular' iniciado por Lenni, Setembro 23, 2024.

  1. Lenni

    Lenni Guest

    I know this is a very basic question. I have a file dinosaur.model.ts where I define an interface, and I also want to define a template

    export interface Dinosaur {
    height: number;
    weight: number;
    lifespan: number;
    diet: string;
    // and 70 other features


    In the same file, I'd like to be able to instantiate an object of the Dinosaur type, and export it as well

    export class customDefaults {
    herbivoreTemplate: Dinosaur = {
    height: 21;
    weight: 6.7;
    lifespan: 65;
    // 71 other features
    }
    carnivoreTemplate: Dinosaur = {
    height: 8;
    weight: 1.7;
    lifespan: 52;
    // 71 other features
    }


    What I need to do is to import the specific instances of my templates into a component, and I know this should be pretty simple, but I cannot make it work. In my-component.ts I'm trying:

    constructor(
    initialHerbivore: Dinosaur,
    ) {
    initialHerbivore = new customDefaults().herbivoreTemplate;


    I've also tried

    export class herbivoreTemplate {
    height: number = 21;
    weight: number = 65;
    // etc.
    constructor(@Inject(Object) obj: Dinosaur) {
    Object.assign(this, obj);
    }
    }


    But there's always an error, whatever I try, and I'm going round in circles. The templates are long, and I need to call them frequently, and I think using an interface for the type, and creating the object instances in the dinosaur.model.ts file is the best approach. I don't want to use a service for this, because I've already got plenty of services running in the background.

    Continue reading...

Compartilhe esta Página