简体   繁体   English

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

[英]Angular Data sharing between two non related components

I am trying to share data between two non related components using service and observable concept but its giving issue.我正在尝试使用服务和可观察概念在两个不相关的组件之间共享数据,但它存在问题。 I have a drop down component and when ever the drop down value changes it needs to update the side nav bar component once the value of drop down is received.我有一个下拉组件,当下拉值发生变化时,一旦收到下拉值,它就需要更新侧导航栏组件。 For this purpose I have simply defined a LOB service which has set and get methods.为此,我简单地定义了一个具有 set 和 get 方法的 LOB 服务。 From DROP DOWN COMPONENT on change method if called in which I am calling set method of LOB Service.如果调用我正在调用 LOB 服务的 set 方法,则从 DROP DOWN COMPONENT 更改方法。 While on ngOnInit inside the Side Nav Component I am calling the get component.在 Side Nav 组件内的 ngOnInit 上,我正在调用 get 组件。 But i am not receiving the value also getting the error.但我没有收到值也收到错误。 Here is my code:这是我的代码:

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

Looking forward to help as I am unable to get value as it gives error unable to read property 'includes' of undefined.期待帮助,因为我无法获得价值,因为它会导致错误无法读取未定义的属性“包含”。 So how to update component and whether to do subscribe on ngOnit or not.那么如何更新组件以及是否在 ngOnit 上订阅。 Thanks谢谢

   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.
   });

move the above code to the constructor and check once this might help you.将上面的代码移动到构造函数并检查一次这可能对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM