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?
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
!
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 = {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With