【问题标题】:Multiple independent instance of same component Angular同一组件Angular的多个独立实例
【发布时间】:2019-03-20 23:48:06
【问题描述】:

我是 Angular 的新手,我试图在应用程序中创建一个多窗口弹出框,并对所有窗口使用相同的组件,我正在使用 ComponentFactoryResolver 加载窗口。

我能够毫无问题地加载一个窗口的多个实例,并且能够将信息传递给新窗口,包括窗口标题(用户名)信息以及消息列表和用户名保持预期的唯一性,但是但是,所有消息都替换为最后一个实例中的任何内容,并将所有消息替换为最后一个实例。

动态内容加载代码:

`loadSingleWindow(user_info)

 {
  const chatBoxFactory = this.componentFactoryResolver.resolveComponentFactory(WindowComponent);
  const viewContainerRef  = this.container;
 // viewContainerRef.clear();

    this.componentRef = viewContainerRef.createComponent(chatBoxFactory);
   // this.chatService.joinChat(user_info);

  const windowInstance = <WindowComponent>(this.componentRef.instance);
  windowInstance.chatUser = user_info;
  this.chatService.loadExistingMessage('').subscribe(data => {
    windowInstance.messages = data;
  });

}
destroyComponent() {
  this.componentRef.destroy();
}
`

WindowComponent 如下所示。

export class ChatWindowComponent implements AfterViewInit {

  public messages: Array<ChatMessage> = [];
  activeRoom: any;

  public chatUser;

  ngAfterViewInit() {
      console.log('hello world');
  }
}

在 WindowComponents 的视图中,我正在循环消息对象以显示 所有消息。

具有相同组件的两个实例且具有唯一标头但消息部分正在替换为最后一个加载的图像:

【问题讨论】:

    标签: angular


    【解决方案1】:

    我可以想象挂起的subscription 是问题所在。使用take 运算符将代码更改为只获取一次值:

    this.chatService.loadExistingMessage('').pipe(
      take(1)
    ).subscribe(data => {
      windowInstance.messages = data;
    });
    

    【讨论】:

    • 它运作良好,谢谢。但是,每当我从一个在所有窗口中接收的窗口发送消息时,我都会再次遇到另一个问题。我试图把这个采取的逻辑放在这个中,但不确定这个采取是如何运作的。构造函数(私人聊天服务:ChatService){ this.chatService.onNewMessageReceived().subscribe(data => { console.log(data); this.messages.push(data); }); }
    • @Koders 您必须以某种方式从消息流中确定应该将其定向到哪个窗口。您可以为此使用filter() 管道
    • 感谢您的建议。
    猜你喜欢
    • 2018-11-21
    • 1970-01-01
    • 2016-10-08
    • 2019-12-28
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    相关资源
    最近更新 更多