Dekso
Dekso

Reputation: 561

How to fill a typescript class model in angular

I created a class model and I don't know how to fill a class with values.

User.ts

export class User {
    constructor(
        username: string,
        password: string,
        token: string
    ) { }
}

app.component.ts

  ngOnInit() {

    let user = new User('uname' , 'pword', 'sampletoken');
    console.log(user);
  }

When I run this, the user is still empty.

enter image description here

Upvotes: 1

Views: 6110

Answers (5)

sibabrat swain
sibabrat swain

Reputation: 1368

I will show you with an example how you can use one class in angular.

items.ts

import { Injectable } from '@angular/core';

@Injectable()
export class Items {
  items: Item[] = [];

  defaultItem: any = {
    "name": "Burt Bear",
    "profilePic": "assets/img/speakers/bear.jpg",
    "about": "Burt is a Bear.",
  };


  constructor(public name: string) {
    let items = [
      {
        "name": "Burt Bear",
        "profilePic": "assets/img/speakers/bear.jpg",
        "about": "Burt is a Bear."
      }
    ];

  }

}

lets check how to grab these data

item-details.ts

import { Items } from '../../providers';

export class ItemDetailPage {
  item: any;

  constructor(items: Items) {
    this.item =  items.defaultItem;
  }

}

Upvotes: 0

Ronak07
Ronak07

Reputation: 894

The alternate way is you can also do this way :-

export class AppComponent  {
  name = 'Angular 6';

  constructor(){
     let user = new User({username: 'abc', password: '1234', token: 1});
     console.log(user);

  }
}


    class User {
        public username?: string;
        public password?: string;
        public token?: number;

        constructor(values: User) {
          Object.assign(this, values);
        }
    }

Here is the link you can check it in console.. CodeSandbox demo

Upvotes: 3

Adrita Sharma
Adrita Sharma

Reputation: 22213

Try like this:

Working Demo

export class User {
  username: string;
  password: string;
  token: string;
  constructor(username: string, password: string, token: string) {
    this.username = username;
    this.password = password; 
    this.token = token;
  }
}

Upvotes: 1

Jins Thomas Shaji
Jins Thomas Shaji

Reputation: 877

Add access specifiers to constructor arguments for making it as a class property. Otherwise it will be considered as, properties in constructor method scope only.

User.ts

export class User {
    constructor(
        public username: string,
        public password: string,
        public token: string
    ) { }
}

Upvotes: 3

StepUp
StepUp

Reputation: 38134

You've forgot to add variables and assign them in constructor:

export class User {
    username: string;
    password: string;
    token: string;

    constructor(username: string,
                password: string,
                token: string) {
         this.username = username;
         this.password= password;
         this.token= token;
    }
}

Upvotes: 1

Related Questions