组件层次结构中的角度传递和覆盖上下文

时间:2018-02-20 04:15:08

标签: angular dependency-injection angular-directive ng-modules

我试图制作组件层次结构。这是一个全球性的"背景"对象(在NgModule级别提供),但我希望一个组件能够为其子级覆盖此对象。 "背景"对象目前通过注射获得,如下所示:

NgModule           ---> Provides default "CONTEXT" for injection
<comp1>
   <comp2>
       <comp3>     ---> Overrides CONTEXT.someProp
           <comp4>
               <comp5>
               <comp5>
           <comp4>
       <comp3>
   <comp2>
<comp1>

没有任何组成部分了解其他人&#39;存在(它们是动态创建的),但comp3应该能够控制/改变上下文&#34;参见&#34;其指定的子女(在这种情况下为comp4和comp5)。

我猜注入不是这里最好的模式(我怎么能这样做?comp3应该扩展CONTEXT吗?),至少因为它是伪静态的(可以在创建后Angular检测并传播设置的变化?)。也许Obse​​rvable可以在这里提供帮助。

我已经看过this answer,但我认为情况不一样。

实现这一目标的最佳方法是什么?我想避免使用显式的@Input属性,因为中间组件应该尽可能不可知。这里有一个共同的模式吗?

1 个答案:

答案 0 :(得分:0)

严格的组件层次结构表明这可以通过分层注入器来解决。

可以在子注入器中指定需要在不同组件中以不同方式配置的提供程序,以便重新实例化。对提供程序配置的需求表明应该有另一个配置提供程序(有关配置配方,请参阅this answer)。例如,具有强制配置的提供程序,如auth服务:

export const SOME_CONFIG = new InjectionToken('someConfig');

@Injectable
export class SomeService {
  config: IConfig;
  constructor(@Optional() @Inject(SOME_CONFIG) someConfig) {
    this.config = {
      /* default config goes here */,
      ...someConfig
    };
  }

  updateConfig(config) {
    return Object.assign(this.config, config);
  }

  ...
}

@NgModule({
  ...
  providers: [
    SomeService,
    { provide: SOME_CONFIG, useValue: { /* global config */ }
  ] 
})
export class AppModule {}

可以使用组件的其他配置创建新实例:

@Component({
  providers: [
    SomeService,
    { provide: SOME_CONFIG, useValue: { /* local config */ }
  ] 
})
class FooComponent {...}