Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly and simply declare an object in Angular2

Tags:

angular

ionic2

I am trying to declare an object and to set the default values in my ionic 2 app, but I don't understand TypeScript and Angular2 very well yet.

I did this:

@Component({
    selector: 'page-weightlevel'
    , templateUrl: 'weightlevel.html'
})
export class WeightlevelPage {

    name: string;
    firstNavParam: boolean;
    data = any;
    data.shareoptions: ['Facebook', 'Twitter', 'Email'];
    data.techniqueText: string;
    data.frequScaleWording: string[];
    data.fitnessWording: string[];
    data.levelName: string[];

    constructor(
        public navCtrl: NavController,
        ....

and I get this error:

Typescript Error
';' expected.
src/pages/weightlevel/weightlevel.ts
data.shareoptions: ['Facebook', 'Twitter', 'Email'];

the dot between data and shareoptions is not welcome apparently.

How can I do this?

like image 334
Louis Avatar asked Mar 24 '17 21:03

Louis


2 Answers

The way to declare/initialize an Object in Typescript is, is by like name says, typing your data. You could go with any, but that just defies the purpose of TypeScript. So instead create a model with desired properties and so declaring an empty object would be:

data: MyType = <MyType>{};

What you are now trying to do is to assign data to your object. For that, use =

ngOnInit() {
  this.data.shareOptions = ['Facebook', 'Twitter', 'Email']
}

As per discussed in comments, you could naturally declare the array inside the Object in the component like so:

data = <MyType>{shareOptions:['Facebook','Twitter','Email']};

Remember though, even with declaring a type, for example interface, it doesn't exist on run time. The typing is just for the compiler to help you and tell you when you are trying to assign values or properties that do not exist in your model. So you can actually override all models and your app will run without error.

But do type your data and avoid using any!

like image 167
AT82 Avatar answered Sep 21 '22 23:09

AT82


in my experience i created object the following way. but i got errors when i ran build script in angular 5.2. then i used second way.

wrong way:

 data = {};

right way:

 data:any = {};
like image 20
Kumaresan Perumal Avatar answered Sep 21 '22 23:09

Kumaresan Perumal