要给出"Angular服务库"的代码示例,首先需要创建一个Angular服务。下面是一个简单的示例:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class ExampleService {
private data: string[] = [];
constructor() { }
addData(item: string) {
this.data.push(item);
}
getData(): string[] {
return this.data;
}
}
import { Component } from '@angular/core';
import { ExampleService } from './example.service';
@Component({
selector: 'app-example',
template: `
- {{ item }}
`,
})
export class ExampleComponent {
data: string[];
constructor(private exampleService: ExampleService) {
this.data = exampleService.getData();
}
addData() {
this.exampleService.addData('New Item');
this.data = this.exampleService.getData();
}
}
import { NgModule } from '@angular/core';
import { ExampleService } from './example.service';
import { ExampleComponent } from './example.component';
@NgModule({
declarations: [
ExampleComponent,
],
providers: [
ExampleService,
],
})
export class ExampleModule { }
以上示例展示了如何创建一个简单的Angular服务库,并在组件中使用它。请根据自己的需求进行更改和扩展。
上一篇:Angular服务就绪标志