Angular Services

@Injectable() 装饰器

对于与特定视图无关并希望跨组件共享的数据及逻辑,可以创建服务类
使用@Injectable() 装饰器,可以让服务作为依赖被注入到其他组件中.
依赖注入DI, 处理冲服务器获取数据, 验证用户输入或直接把日志写到控制台.

serviceDemo

1
2
3
4
5
6
7
8
9
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class CalculatorService {
add(x: number, y: number) {
return x + y;
}
}

usage

1
2
3
4
5
6
7
8
9
@Component({
selector: 'app-receipt',
template: `<h1>The total is {{ totalCost }}</h1>`,
})
export class Receipt {
// 在非构造函数中使用
private calculatorService = inject(CalculatorService);
totalCost = this.calculatorService.add(50, 25);
}

本文作者: 孟 虎
本文链接: https://menghu1994.github.io/blog/FrontEnd/FrontEnd/Angular/Services/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!