Search code examples
angulartypescriptangular7

How to call value from a class to another in angular


I'm trying to import variables which are from Items class, but I can't figure out how it should be done. Heres an example of my code,

item.ts:

export class Item{
   itemName: string;
   id: sstring;
}

user.ts

import {Item} from './item'

export class Users{
   username: string;
   id: string;
}

The question is how can I get the value itemName inside the user.ts.


Solution

  • These look a lot like models. So you are defining the structure of what a user and item should look like with some typing restrictions. You could add an item to a user's model like so.

    import {Item} from './item'
    
    export class Users{
       username: string;
       id: string;
       item: Item;
    }
    

    This will type Users.item to your Item class. Just to clarify you would therefore have itemName under user.item.itemName