我有一个有角度的应用程序,其中包含一个显示用户活动的木板。该板仅在应用程序的某些区域中可见。板上的数据不应保留在DB中。在浏览该应用程序时,我发现每次都会创建一个新的木板实例,因此前一个木板所包含的所有数据都会丢失。
我曾尝试将所有数据复制到Singleton服务中并将其拉回,但这似乎很繁琐
因此,我尝试创建一个共享组件实例并将其添加到所需的视图中,但这没有用
app.component.ts
export class AppComponent implements OnInit...{
service ;//Singleton service
constructor(private injector: Injector,private resolver: ComponentFactoryResolver){
const factory = this.resolver.resolveComponentFactory(BoardComponent);
const componentRef = factory.create(this.injector);
this.service.setComponentRef(componentRef);
}
......
}
在特定视图下,我尝试插入组件实例
@Component({
templateUrl: `<ng-template #vwRef></ng-template><br/> <p>User Log</p>.......`,
selector: "supervisor-panel",
styleUrls: ["./supervisor-panel.component.css"],
})
export class SupervisorViewComponent implements OnInit...{
@ViewChild("vwRef",{read: ViewContainerRef})
refTemplate: ViewContainerRef;
constructor(private service : SingletoneService){ }
ngOnInit(){
let componentRef = serivce.getComponentRef();
this.refTemplate.insert(componentRef.hostView);
}
}
这会导致错误
错误TypeError:无法读取未定义的属性'_lView' 在ViewContainerRef.insert(http:// localhost:4200 / vendor.js:33661:81)
这是正确的方法还是有替代解决方案?
答案 0 :(得分:0)
在这种情况下,您可以使用localStorage,它在全局范围内可用,并且数据将持久保存。
答案 1 :(得分:0)
这种方法是错误的,您应该将状态管理库用于此类操作,或者,如果您的应用程序很小,或者组件之间没有大量共享数据,则只需在单例服务上创建Observable。 / p>
基本上,您将创建一个全局可观察变量,侦听该组件中的更改以执行更改后需要执行的操作,然后您可以使用任何组件中的新值在该可观察对象上调用“ next”想要