Search code examples
angulartypescriptclass

Import an instance of a class into an Angular component


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.


Solution

  • Instead of creating a customDefaults class, you could simply export your "instances" in the dinosaur.model.ts file :

    export const herbivoreTemplate: Dinosaur = {
        height: 21;
        weight: 6.7;
        lifespan: 65;
        // 71 other features
    }
    

    And then you could import it like import { herbivoreTemplate } from 'dinosaur.model.ts' and use it like any other variable.

    Beware tho that the const keyword only forbid reassignation but since you are dealing with a global variable you have no guarantee that the values in your template won't be modified. (This issue also is present with your approach)

    As side notes, you don't "instantiante" interfaces, your instantiate classes. Interfaces are used to describe the "shapes" of classes.

    Also, depending on your usecase, you might want to define a type instead of an interface: export type Dinosaur = { [...] };. Going into the differences between those two is a lengthy discussion, but you can read the official doc : https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces