angular - 如何从组件初始化服务?
问题描述
我在每个组件中使用单独的服务实例:
@Component({
selector: 'app-orders',
templateUrl: './orders.component.html',
styleUrls: ['./orders.component.scss'],
providers: [PaginationService],
})
服务分页是:
@Injectable()
export class PaginationService {
private offset: number;
private limit: number;
constructor() {
this.offset = 0;
this.limit = 20;
}
}
如您所见,服务在构造函数中进行了初始化。如何从特定组件初始化服务,例如:
providers: [PaginationService(0, 20)],
解决方案
您可以使用工厂提供程序,如下所示:
@Component({
selector: 'app-orders',
templateUrl: './orders.component.html',
styleUrls: ['./orders.component.scss'],
providers: [
{
provide: PaginationService,
useFactory: () => new PaginationService(0, 20)
}
],
})
您可以在此处的 Angular 文档中找到更多示例。
推荐阅读
- python - 从 Django 中的 Dict 获取价值
- javascript - 如何使用Django将python列表传递给javascript数组
- amazon-web-services - 使用 lambdafunction AWS 注释的单元测试接口
- service-worker - 如何生成 browserslist 范围以匹配功能支持?
- csv - Jmeter在从csv文件读取数据时显示错误,我已经尝试了所有可能的步骤,但我仍然无法弄清楚我做错了什么
- api - 将 Heroku 的临时存储同步到 Dropbox
- validation - 纪念碑 AI 导入数据不正确
- c# - Protobuf-net 将对象实例追加到流中,反序列化为列表
- javascript - 如何使用正则表达式替换 HTML 标签中的换行符?
- powershell - Process.StandardOutput.ReadToEnd() 始终为空