要在Angular中使用类和接口,可以按照以下步骤进行:
ng new my-app
cd my-app
person.ts
:touch person.ts
person.ts
文件中,定义一个Person类和一个IPerson接口:export class Person {
firstName: string;
lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
}
export interface IPerson {
firstName: string;
lastName: string;
getFullName(): string;
}
app.component.ts
文件中:import { Component } from '@angular/core';
import { Person, IPerson } from './person';
@Component({
selector: 'app-root',
template: `
Hello {{ person.getFullName() }}
`,
})
export class AppComponent {
person: IPerson;
constructor() {
this.person = new Person('John', 'Doe');
}
}
app.module.ts
文件,将AppComponent添加到@NgModule
的declarations
和bootstrap
数组中:import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
ng serve
http://localhost:4200
,你将看到输出Hello John Doe
。这是一个简单的示例,展示了如何在Angular中使用类和接口。你可以根据自己的需求进一步扩展和修改代码。