两个不相关组件之间的角度数据共享



我正试图使用服务和可观察概念在两个不相关的组件之间共享数据,但这是一个给定的问题。我有一个下拉组件,当下拉值发生变化时,它需要在收到下拉值后更新侧导航栏组件。为此,我简单地定义了一个LOB服务,它具有set和get方法。如果调用了DROP DOWN COMPONENT on change方法,我将在其中调用LOB服务的set方法。在侧面导航组件内的ngOnInit上,我正在调用get组件。但是我没有收到值也得到了错误。这是我的代码:

1.drop down component: 
onChange(event): void {  
const newVal = event.target.value;
this.PreSelectedDropDown=newVal;
this.lobService.SetLOB(newVal); //service set method called

}
2. Side bar component : //Subscribing to observable in ngOninit()
this.lobService.GetLOB.subscribe(valData =>{
this.dropDownSelected=valData;
console.log(this.dropDownSelected + " -- inside side nav getting value");
this.createNavList();//Calling create nav when ever new drop down value comes up so component is recreated.
});

3. Service for data sharing bw two components: 
export class LobmenuService {
data:string="";
constructor() { }
private getLOB: BehaviorSubject<any> = new BehaviorSubject<any>(null);
GetLOB: Observable<any> = this.getLOB.asObservable();
setLOB(plan: any) {
this.getLOB.next(plan);
}
}

期待帮助,因为我无法获得值,因为它给出了无法读取未定义的属性"includes"的错误。那么如何更新组件以及是否订阅ngOnit。感谢

2. Side bar component : //Subscribing to observable in ngOninit()
this.lobService.GetLOB.subscribe(valData =>{
this.dropDownSelected=valData;
console.log(this.dropDownSelected + " -- inside side nav getting value");
this.createNavList();//Calling create nav when ever new drop down value comes up so component is recreated.
});

将上面的代码移到构造函数中并检查一次,这可能会对您有所帮助。

最新更新