簡體   English   中英

Angular 2 DI:將輸入綁定傳遞給工廠提供者的部門

[英]Angular 2 DI: pass input binding to deps of factory provider

有沒有一種簡單的方法可以將輸入綁定注入提供者工廠的 deps 數組? 下面顯然不起作用。

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

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

作為一種可能的解決方案,您可以嘗試這樣做:

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 示例

接受的答案效果很好,但是如果您的組件“提供”了幾個相互依賴的依賴項,那么事情就會變得更加復雜。

如果您已經大量使用可觀察對象,另一種可能有效的方法是提供一個LAZY_ID令牌,它實際上是一個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 ]
    },

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM