我是 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 ,但消息部分将替换为最后一个加载的内容:
最佳答案
我可以想象挂起的订阅
就是问题所在。将代码更改为使用 take
运算符仅获取一次值:
this.chatService.loadExistingMessage('').pipe(
take(1)
).subscribe(data => {
windowInstance.messages = data;
});
关于angular - 同一组件 Angular 的多个独立实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55264357/