接受的答案效果很好,但是如果您的组件“提供”了多个相互依赖的依赖项,那么事情就会变得更加复杂。
如果您已经大量使用 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 ]
},