【问题标题】:Load generic angular dynamic component加载通用角度动态组件
【发布时间】:2019-08-01 08:13:16
【问题描述】:

我正在尝试为弹出窗口制作一个动态组件,以便为不同的内容创建视图和编辑页面。我制作了一个弹出组件,我想在其中传递一个新的组件名称和页面标题。但是,我没有在弹出组件中获得新的组件数据。请查看代码,如果您需要更多详细信息,请询问。提前致谢。

我尝试在另一个组件中注入服务,它会在单击按钮时获取数据,但在弹出组件中,我没有获取数据。目前,我只是将 console.log 数据写入 popup.component.ts 文件,但在 console.log 中没有结果。

popup.service.ts

export class PopupService {
    isShowing = false;
    private popup = new Subject();
    loadingPopup = new Subject();
    outputEmitter = new Subject();
    popupContent: any = {
        isShowing: false,
        content: null,
        contentParams: PopupModel
    }
    constructor() { }
    public getPopup() {
        return this.popup;
    }
    public showLoading(isLoading: boolean = true) {
        this.loadingPopup.next(isLoading);
    }
    public create(component: any, parameters?: PopupModel): any {     
        this.showLoading(true);
        this.popupContent.isShowing = true;
        this.popupContent.content = component;
        this.popupContent.contentParams = parameters;
        this.popup.next(this.popupContent);
        console.log(this.popupContent)
    }
}

Popupcomponent.ts

export class PopupComponent implements OnInit, OnDestroy {

public popupObservable: Subscription;

constructor(private popupService: PopupService) { }

ngOnInit() {
this.popupObservable = this.popupService.getPopup().subscribe((popupContent: any) => {
console.log(popupContent)
//code here to use createDynamicComponent method }
}
private createDynamicComponent(component: Type<any>): void {
//code here using ComponentFactoryResolver and ViewContainerRef to create dynamic component
}
ngOnDestroy() {
    if (this.popupObservable && !this.popupObservable.closed) {
      this.popupObservable.unsubscribe();
    }
  }
}

这是调用动态组件并应创建弹出窗口的代码。 组件.ts

AddRecord(){
    this.popupService.create( NewRecordComponent, {
      title: 'Add',
      emitterMethod: 'saved'
    })
  }

component.html

<button (click)="AddRecord()">Add</button>

【问题讨论】:

  • 如果你能提供一个小的复制你的问题会很好。我个人觉得很难理解工作流程。

标签: angular-dynamic-components angular-v7


【解决方案1】:

您不会在任何地方从您的主题中发出值。
您需要致电popup.next(popupContent)

但是,我认为您在这里没有合适的模型。
如果您没有在 getPopup 方法中进行任何异步调用(api、文件系统等),则直接返回 popupContent

public getPopup() : {} {
        return this.popupContent;
    } 

您还应该在某处为您的 popupContent 定义一个接口,以便您可以导入它并使用强大的接口来避免运行时错误。

例如

export interface IPopupContent {
  isShowing: boolean;
  content: string;
  contentParams: PopupModel;
}

另外,不要直接公开主题,而是公开链接到主题的可观察对象。

When to use asObservable() in rxjs?

【讨论】:

  • 感谢您的回答,我在 creat() 方法中调用了 popup.service.ts 中的 popup.next(popupContent) 并且 console.log 给了我 popupContent 对象。如果我在弹出组件本身的任何其他组件中订阅弹出主题,我会得到该对象。这就是为什么没有得到我正在发生的确切问题。
  • 啊,我现在明白了。您将需要 BehaviourSubject,它存储最后发出的值以供将来调用订阅。
猜你喜欢
  • 2017-07-19
  • 2022-01-04
  • 2017-10-10
  • 2019-07-11
  • 2020-02-25
  • 2019-07-15
  • 2017-11-02
  • 1970-01-01
  • 2019-07-22
相关资源
最近更新 更多