我想创建一个服务,其中存储了angular组件的对象。该服务基本上会有一个类似于{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。这意味着问题出在别处。也许是因为我在component类之外调用服务。
https://stackoverflow.com/questions/38502870
复制相似问题