Creating model classes in TypeScript

后端 未结 3 1370
别跟我提以往
别跟我提以往 2021-02-01 12:48

Hi I am new to TypeScript and I come from both a C# and JavaScript background. I am trying to create a way that allows me to create class models similar to what we can do in C#.

3条回答
  •  清酒与你
    2021-02-01 12:51

    Yes, you can do it.

    Step 1: Create your model using “Classes”. While TypeScript has interfaces that can provide this functionality, the Angular team recommends just using a bare ES6 class with strongly typed instance variables. ES6 classes allow you to (optionally) build out functionality around your models and also doesn't require you to be locked into a TypeScript specific feature. For these reasons, it's advisable to use classes for creating models.

    export class DonutChartModel {
    
    //Fields 
    dimension: Number
    innerRadius: Number
    backgroundClass: Number
    backgroundOpacity: Number
    myPropertyToSet: String 
    
    constructor (dimension: Number, innerRadius: Number){
       this.dimension = dimension
       this.innerRadius = innerRadius
    }}
    

    Step 2: Import it into your component. This will give you the added benefit of reuse the data model in multiple places.

    import { DonutChartModel } from '../../models/donut-chart-model;
    

    Step 3: Set one of the properties values:

    export class MenuSelectionPage {
    
     myDonuts: DonutChartModel[] = [];
    
     constructor(public navCtrl: NavController, public navParams: NavParams) {
      this.FillLocalData()
      this.myDonuts[this.myDonuts.length - 1].myPropertyToSet = "I am your father" 
     } 
    
    //Aux Methods
    FillLocalData() {
    let dimensions = [8.32, 5, 17];
    let defaultInnerRadius = 2;
    for (let i = 0; i < dimensions.length; i++) {
      let donut = new DonutChartModel (dimensions[i], defaultInnerRadius * i)
      this.myDonuts.push(donut)
    }}}
    

    Step 4 (Optional): Use it in html.

     ...
     
        
     
     ...
    

    Note: This code has been tested in ionic 3

提交回复
热议问题