为组件的多个实例提供提供者的单个实例
Providing a single instance of a provider for multiple instances of a component
我正在使用以下代码动态创建一个组件
addPhone(): void {
const widgetFactory = this._resolver.resolveComponentFactory( PhoneComponent );
this.createdWidgetRef =
this.container.createComponent( widgetFactory );
this.createdWidgetRef.instance.index = this.container.length - 1;
this.createdWidgetRef.instance.containerRef = this.container;
++this.containerIndex
}
组件创建成功。
我有一个 ObservableMap,我希望只有一个实例用于动态创建的 PhoneComponent 的所有实例。我不能将这个 ObservableMap 放在 PhoneComponent 中,因为将为每个 PhoneComponent 实例创建一个新的地图实例(至少现在是这样)。将 ObservableMap 作为服务注入时会发生这种情况。
有什么方法可以使用 angular2 服务来完成这个任务吗?
注意:输入到 PhoneComponent 的不同实例中的所有数据都应插入到 ObservableMap 的单个实例中 - 因此组件的多个实例只能存在一个实例。
此外,我无法使用 bootstrap 中的提供程序,因为我还需要将 ObservableMap 用于其他组件(例如 EmailComponent)。
在 NgModule
中提供服务,而不是延迟加载
@Injectable()
export class SharedMapService {
private _sharedMap = {};
get sharedMap() { return this._sharedMap; }
}
@NgModule({
imports: [...],
declarations: [...],
providers: [SharedMapService],
})
export class AppModule {}
将此构造函数添加到您的 PhoneComponent
constructor(private sharedMap:SharedMapService) {
console.log(sharedMap.sharedMap);
}
我正在使用以下代码动态创建一个组件
addPhone(): void {
const widgetFactory = this._resolver.resolveComponentFactory( PhoneComponent );
this.createdWidgetRef =
this.container.createComponent( widgetFactory );
this.createdWidgetRef.instance.index = this.container.length - 1;
this.createdWidgetRef.instance.containerRef = this.container;
++this.containerIndex
}
组件创建成功。
我有一个 ObservableMap,我希望只有一个实例用于动态创建的 PhoneComponent 的所有实例。我不能将这个 ObservableMap 放在 PhoneComponent 中,因为将为每个 PhoneComponent 实例创建一个新的地图实例(至少现在是这样)。将 ObservableMap 作为服务注入时会发生这种情况。
有什么方法可以使用 angular2 服务来完成这个任务吗?
注意:输入到 PhoneComponent 的不同实例中的所有数据都应插入到 ObservableMap 的单个实例中 - 因此组件的多个实例只能存在一个实例。
此外,我无法使用 bootstrap 中的提供程序,因为我还需要将 ObservableMap 用于其他组件(例如 EmailComponent)。
在 NgModule
中提供服务,而不是延迟加载
@Injectable()
export class SharedMapService {
private _sharedMap = {};
get sharedMap() { return this._sharedMap; }
}
@NgModule({
imports: [...],
declarations: [...],
providers: [SharedMapService],
})
export class AppModule {}
将此构造函数添加到您的 PhoneComponent
constructor(private sharedMap:SharedMapService) {
console.log(sharedMap.sharedMap);
}