7

有没有一种简单的方法可以将输入绑定注入到提供者工厂的 deps 数组中?下面显然不起作用。

const myServiceFactory = (object: any) => {
   //...
};

@Component({
    // ...
    inputs: ['object'],
    providers: [
        {
            provide: Object,
            useValue: object,
        },
        {
            provide: MyService,
            useFactory: myServiceFactory,
            deps: [Object]
        }
    ]
})
4

2 回答 2

12

作为一种可能的解决方案,您可以尝试这样做:

const myServiceFactory = (self: Child) => {
  return new MyService(self.param);
};

class MyService {
  constructor(private param: string) {}
}
@Component({
  selector: 'child',
  template: `{{ param }}`,
  providers: [
    {
      provide: MyService,
      useFactory: myServiceFactory,
      deps: [Child]
    }
  ]
})
export class Child {
  @Input() param: any;

  constructor(private inj: Injector) { }

  ngOnInit() { // or ngOnChanges
    let service = this.inj.get(MyService);
  }
}

Plunker 示例

于 2017-03-04T08:19:53.673 回答
1

接受的答案效果很好,但是如果您的组件“提供”了多个相互依赖的依赖项,那么事情就会变得更加复杂。

如果您已经大量使用 observables,另一种可能有效的方法是提供一个LAZY_ID实际上是 a ReplaySubject<number>(或您需要的任何类型)的令牌。

在您中ngOnInit(),您只需调用通过传入的值this.lazyID.next(this.id)来更新。ReplaySubject@Input

此外,您可以将它LAZY_ID与提供者工厂一起使用来创建主要依赖项。

免责声明:我认为这不是解决这个问题的好方法。它可能会变得笨拙,但有时它可能会起作用!

这是一个简化的示例-欢迎改进:

export const LAZY_ID = new InjectionToken<ReplaySubject<number>>('LAZY_ID');

export const LazyIDFactory = () => 
{
    return new ReplaySubject<number>(1);
}


export const productDataFromLazyIDFactory = (productService: ProductService, id$: ReplaySubject<number>) =>
{
    // Create your 'ProductData' from your service and id$
    // So yes - the catch here is your ProductData needs to take an observable
    // as an input - which only really works if you're extensively using observables
    // everywhere. You can't 'wait' for the result here since the factory must return
    // immediately
}

然后在你的@Component

providers: [ 

    // creates our ReplaySubject to hold the ID
    {
        provide: LAZY_ID,
        useFactory: LazyIDFactory
    },
    { 
        provide: ProductData,
        useFactory: productDataFromLazyIDFactory,
        deps: [ ProductService, LAZY_ID ]
    },
于 2019-08-13T20:13:54.503 回答