我在Angular 6中创建了名为“ DeleteDirective
”的指令,并引用了服务“ DeleteService
”,以确保可以从应用程序中删除项目。将该项目标记为已删除之后(在PHP后端),我将通过在UndoComponent
中动态添加的'DeleteService
'显示一个Undo元素。到目前为止没有问题。
@Directive({
selector: '[appDelete]'
})
export class DeleteDirective {
constructor(
@Inject(ViewContainerRef) viewContainerRef,
renderer: Renderer2
) {
service.renderer = renderer;
service.setRootViewContainerRef(viewContainerRef);
service.addUndoElement();
}
@HostListener('click') onClick() {
// (Some code to execute deletion)
this.deleteService.showUndoElement();
}
@Injectable({
providedIn: 'root'
})
export class DeleteService {
constructor(
rendererFactory: RendererFactory2,
private factoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
) {
this.renderer = rendererFactory.createRenderer(null, null);
this.factoryResolver = factoryResolver;
}
setRootViewContainerRef(viewContainerRef) {
this.rootViewContainer = viewContainerRef;
}
addUndoElement() {
const factory = this.factoryResolver.resolveComponentFactory(UndoComponent);
const component = factory.create(this.rootViewContainer);
// this.rootViewContainer.insert(component.hostView);
this.appRef.attachView(component.hostView);
const domElem = (component.hostView as EmbeddedViewRef<any>)
.rootNodes[0] as HTMLElement;
document.body.appendChild(domElem);
}
}
现在,在UndoComponent HTML中,我创建了一个名为restoreItem
的链接来撤消操作。我想使用另一个名为ListService
的服务来再次获取一些数据。
@Injectable()
export class UndoComponent implements OnInit {
constructor(private listService: ListService) {
}
restoreItem() {
this.currentList = this.listService.getSelectedList();
console.log(this.currentList); // null
}
}
看来我无法从此动态添加的组件到DOM引用ListService
(或任何其他服务)。它返回null
。关于如何从动态添加的组件访问服务的任何想法?非常感谢任何指示!
编辑:添加了Listservice
存根代码以进行澄清
@Injectable({
providedIn: 'root'
})
export class ListService {
lists: List[];
list: List[];
currentList: List;
constructor(private http: HttpClient) { }
setSelectedList(list: List): void {
this.currentList = list;
}
getSelectedList(): List {
return this.currentList;
}
private handleError(error: HttpErrorResponse) {
console.log(error);
return throwError('Error! something went wrong.');
}
}
答案 0 :(得分:0)
您是否仍要在ListService中设置currentList的值。
永远不会调用ListService中的setSelectedList,它用于设置currentList的值。因此currentList保持为空。