javascript - 组件之间的数据传输

标签 javascript angular typescript events rxjs

组件A内部有2个组件:

    <div class="classStyleLeft">
        <app-picture [IdSectionPicture]="2" [PData]="modelPage"></app-picture>          
    </div>
    <div class="classStyleRight">     
        <app-list [IdSectionList]="2" [PData]="modelPage"></app-list>
    </div>

在组件 app-list 中,从列表中选择一个项目并单击方法 showInfo:

    <ul *ngFor="let value of PData.content[IdSectionList].content; let valueIndex = index;">
      <li (click)="showInfo(IdSectionList, valueIndex)">
        <b>{{value.value}}</b>
      </li>
    </ul>

我想要将方法参数 showInfo 传递给组件 app-picture。组件内容app-picture:

<div>{{PData.content[IdSectionList].value[valueIndex].value}}</div>

我不知道怎么做。

我会寻求帮助。 谢谢

最佳答案

使用服务共享数据是不够的,因为必须监听事件。 由于它是同级组件,因此使用 BehaviorSubject 创建一个服务为:

export class InfoService{
   private infoSubject = new BehaviorSubject<any>({id: '',value: ''});

   showInfoEventEmitter(data){
     this.infoSubject.next(data);
   }

   showInfoEventListener(){
     return this.infoSubject.asObservable();
   }

}

然后在组件中使用它作为

app-list.component

constructor(public infoSvc: InfoService){}

showInfo(IdSectionList, valueIndex){
   this.infoSvc.showInfoEventEmitter({id:IdSectionList, value:  valueIndex})
}

并且在app-picture.component

eventSubscription: Subscription;
constructor(public infoSvc: InfoService){}

ngOnInit(){
  this.eventSubscription = this.infoSvc.showInfoEventListener().subscribe(res => {
      console.log(res); // you have the event here
   })
}

ngOnDestroy(){
  this.eventSubscription.unsubscribe(); // to stop listening to this event after component is destroyed
}

关于javascript - 组件之间的数据传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57303137/

相关文章:

angular - 在 Angular2 测试中正确注入(inject)依赖项

angular - 强制 Angular 分量在按下后退按钮时重新加载

javascript - 无法访问传递给 Angular 组件的 @Input 字段的对象中的公共(public)方法

reactjs - 类型 'TableInstance{}' 上不存在 react 表分页属性

javascript - JS 切换不起作用

javascript - 如何获取回复文本?

javascript - 减少条形间距 ChartJS v2

javascript - 网络图像未在 React Native 中显示

javascript - 迭代回调 hell (ClojureScript 中)

reactjs - react /TSX : child unable to infer correct generic type from parent