How do I declare a model class in my Angular 2 component using TypeScript?

后端 未结 8 739
野趣味
野趣味 2020-12-23 11:10

I am new to Angular 2 and TypeScript and I\'m trying to follow best practices.

Instead of using a simple JavaScript model ({ }), I\'m attempting to create a TypeScri

8条回答
  •  没有蜡笔的小新
    2020-12-23 11:31

    export class Car {
      id: number;
      make: string;
      model: string;
      color: string;
      year: Date;
    
      constructor(car) {
          {
            this.id = car.id;
            this.make = car.make || '';
            this.model = car.model || '';
            this.color = car.color || '';
            this.year = new Date(car.year).getYear();
          }
      }
    }
    

    The || can become super useful for very complex data objects to default data that doesn't exist.

    . .

    In your component.ts or service.ts file you can deserialize response data into the model:

    // Import the car model
    import { Car } from './car.model.ts';
    
    // If single object
    car = new Car(someObject);
    
    // If array of cars
    cars = someDataToDeserialize.map(c => new Car(c));
    

提交回复
热议问题