首页 > 解决方案 > 如何从组件初始化服务?

问题描述

我在每个组件中使用单独的服务实例:

@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)],

标签: angularangular8

解决方案


您可以使用工厂提供程序,如下所示:

@Component({
  selector: 'app-orders',
  templateUrl: './orders.component.html',
  styleUrls: ['./orders.component.scss'],
  providers: [
    {
      provide: PaginationService,
      useFactory: () => new PaginationService(0, 20)
    }
  ],
})

您可以在此处的 Angular 文档中找到更多示例。


推荐阅读