Classes

Learn about classes and constructors.

Class-based object-oriented programming

In the TypeScript lesson, we discussed the importance and relevance of classes in providing a standardized method of generating a blueprint from which objects could be created (or, for the more technical term, instantiated).

Class-based object-oriented programming is implemented within Ionic through the use of Angular/TypeScript and would resemble something akin to the following fictional component and included service:

Press + to interact
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DatabaseService} from '../../services/database.service';
@Component({
selector: 'app-equipment-items',
templateUrl: 'equipment-items.page.html',
styleUrls: ['equipment-items.page.scss'],
})
export class EquipmentItemsPage implements OnInit {
public items : Array<any>;
constructor(private router : ActivatedRoute , private db : DatabaseService) { }
ngOnInit() {
let urlParam : string = this.router.snapshot.paramMap.get('id');
this.items = this.db.retrieveSingleRecord(urlParam);
}
public viewEquipmentItem(item : any): void {
console.log(item.name); this.router.navigateByUrl('/' + item.name);
}
}

File structure

Here’s how the structure of the above script breaks down:

  • Imported modules
  • Class decorator
  • Class declaration
  • Constructor

Imported modules

Modules and packages required for use in Ionic classes are brought in through import statements at the top of the TypeScript file.

In the above example, we are importing the following modules, from lines 1 to 3: ...