Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 为组件提供依赖于组件@Input的服务实例_Angular_Input_Service_Dependency Injection - Fatal编程技术网

Angular 为组件提供依赖于组件@Input的服务实例

Angular 为组件提供依赖于组件@Input的服务实例,angular,input,service,dependency-injection,Angular,Input,Service,Dependency Injection,我有一个包含子栅格和详图构件的主详图构件 基于@Input entityType参数,网格和详图组件需要将其特定的dataService属性初始化为DataService1、DataService2、。。。或数据服务。 实现这一目标的最佳方式是什么?我看到了各种可能性: 使用createServiceInstance(entityType)方法创建@Injectable工厂服务: public createService(type: EntityType): any { switch (

我有一个包含子栅格和详图构件的主详图构件

基于@Input entityType参数,网格和详图组件需要将其特定的dataService属性初始化为DataService1、DataService2、。。。或数据服务。 实现这一目标的最佳方式是什么?我看到了各种可能性:

  • 使用
    createServiceInstance(entityType)
    方法创建
    @Injectable
    工厂服务:

    public createService(type: EntityType): any {
        switch (type) {
            case EntityType.Type1:
                return new DataService1();
            case EntityType.Type2:
                return new DataService2();
            case EntityType.TypeN:
                return new DataServiceN();
        }
    }
    
    然后将该服务注入主细节组件构造函数并分配do

    this.dataService = this.factoryService.createService(entityType)
    
    在ngOnInit/ngOnChanges中。然后,我们将@Input dataService添加到网格和细节组件,并将其绑定到masterDetail dataService属性

  • 在细节/网格组件中使用注入器服务,将@Component decorator的providers属性设置为[DataService1,DataService2,…,DataServiceN],然后在Ngonit中设置

    this.dataService = this.injector.get(getDataService(entityType))
    
    this.dataService = this.factoryService.getDataService(entityType)
    

  • 混合使用1)和2):在ServiceFactory的构造函数中为其提供[DataService1,DataService2,…,DataServiceN],然后详细说明/grid component

    this.dataService = this.injector.get(getDataService(entityType))
    
    this.dataService = this.factoryService.getDataService(entityType)
    

  • 另一个解决方案


  • 我将Angular 4与TypeScript一起使用。

    我遇到了类似的问题,并找到了以下工作解决方案:

    我有接口文件服务:

    export interface FileService {
        downloadDocument(ownerId: string, fileId: string): Observable<any>;
    }
    
    现在,在父组件中,我可以决定应该在组件的这个实例中使用哪个服务:

    <app-some-test-component [fileService]="fileServiceImpl" ></app-some-test-component>
    
    
    

    这种方法意味着您不需要提供字符串来决定使用哪个服务,而需要提供服务本身。

    没有客观标准,就没有“最佳方法”。你试过这些吗?进展如何?我尝试了解决方案1和2,两者都不错,但更多的是关于代码质量和最佳实践。例如,我不喜欢使用new()实例化服务,并在解决方案1)的主细节组件中保留一个引用。在解决方案2中),我们直接在主细节中提供所有服务,这也是某种形式的耦合,我也不希望有。这就是为什么我认为第三种选择可能是一个很好的候选人,但我可能忽略了其他一些可能性
    <app-some-test-component [fileService]="fileServiceImpl" ></app-some-test-component>