服务

时间:2016-07-21 11:19:24

标签: angularjs angular angular2-services

我想创建一个存储角度组件对象的服务。该服务基本上会有一个属性组件,看起来像{key: componentClass}

实现起来似乎很简单,实际上是,但我遇到了一个问题,我不知道如何解决它。

允许致电服务ComponentStoreService。作为一个例子,它可能看起来像这样:

@Injectable()
export class ComponentStoreService {
 components: { [key: string]: any; } = {};

   register(key: string, components: any): void {
     this.components[key] = components;
   }

   getByKey(key: string): any {
     return this.components[key];
   }

   getAll(): any {
     return this.components;
   }
}

现在让我们创建2个演示组件并存储它们。:

const providers = ReflectiveInjector.resolve([ComponentStoreService]);
const injector = ReflectiveInjector.fromResolvedProviders(providers);
const componentStore= injector.get(ComponentStoreService );

@Component({
  selector: 'component-1',
  template: `<h2>component-1</h2>`
})
export class D1Component {constructor() {}}

componentStore.register('component-1', D1Component );

console.log('component-1 called', componentStore.getAll())

第二个:

    const providers = ReflectiveInjector.resolve([ComponentStoreService]);
    const injector = ReflectiveInjector.fromResolvedProviders(providers);
    const componentStore= injector.get(ComponentStoreService );

    @Component({
      selector: 'component-2',
      template: `<h2>component-2</h2>`
    })
    export class D2Component {constructor() {}}

    componentStore.register('component-2', D2Component );

    console.log('component-2 called', componentStore.getAll())

结果,第一个console.log打印出第一个添加组件的对象。哪个好。第二个console.log仅打印第二个组件。这是不正确的。

据我所知,每个组件ComponentStoreService都是单独的实例。我怎么能在整个应用程序中使它单身?我只在应用级别注册ComponentStoreService。这意味着问题出在其他地方。也许是因为我在组件类之外调用服务。

1 个答案:

答案 0 :(得分:1)

您的ComponentStoreService是全局服务。因为您在多个组件中使用该服务。您可以在加载应用程序时将其注入一次。所以您可以在任何地方使用它。

bootstrap(AppComponent, [ComponentStoreService]);

组件1:

    @Component({
      selector: 'component-1',
      template: `<h2>component-1</h2>`
    })
    export class D1Component {constructor(private _componentStoreService:ComponentStoreService) {}}

    componentStore.register('component-1', D1Component );

    console.log('component-1 called', this._componentStoreService.getAll())

COMPONENT2

        @Component({
          selector: 'component-2',
          template: `<h2>component-2</h2>`
        })
        export class D2Component {constructor(private _componentStoreService:ComponentStoreService) {}}

        componentStore.register('component-2', D2Component );

        console.log('component-2 called', this._componentStoreService.getAll())

您可以使用提供程序注入ComponentStoreService。