angular - 同一组件 Angular 的多个独立实例

标签 angular

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

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

dynamic content loading code:

`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');
  }
}

In the view of WindowComponents I am looping messages object to show all message.

具有同一组件的两个实例的图像,具有唯一的 header ,但消息部分将替换为最后一个加载的内容:

Image with two instances of the same component with a unique header but message part is replacing by whichever load in the last

最佳答案

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

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

关于angular - 同一组件 Angular 的多个独立实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55264357/

相关文章:

json - Angular2 Http.Post - 如何查看 webapi 响应

angular - 在 Angular 模板中创建和格式化日期

Angular 8 出现类似属性 'ASSIGNMENT' 的错误在类型 '[]' 上不存在

javascript - Typescript 文件在 vs2017 中自动创建 Javascript,无需 tsconfig.json 全局项目级别

angular - ngx-datatable 未在我的 component.html 中呈现

typescript - Angular 2 - 如何将依赖项注入(inject)到不是组件且未作为服务公开的自定义类

angular - : 'component selector' is not a known element: running ng-build on angular 5 app 中出现错误

javascript - CSS设置以在向下滚动时修改元素

javascript - Angular Material Checkbox 不会改变选中的状态

Angular :将输入值重置为之前的值