How do I share data between sibling components in angular?

前端 未结 4 1312
轮回少年
轮回少年 2021-02-04 08:08

I have an Angular application with 3 sibling components, they are able to access and update the variable \"data\". They are connected to the router, but the data I want to pass

4条回答
  •  暖寄归人
    2021-02-04 08:55

    Since you have asked to share the data between sibling components we can achieve it by using BehaviourSubject in service.

    The BehaviorSubject holds the value that needs to be shared with other components. These components subscribe to data which is simple returning the BehaviorSubject value without the functionality to change the value.

    Service.ts

    import { Observable, BehaviorSubject } from 'rxjs';
    
    export class Service {
           private data = new BehaviorSubject("")
           currentData = this.data.asObservable();
    
     constructor() { }
    
     setData(data) {
          this.data.next(data);
     }
    

    Component1.ts

    import { Service } from '../service.service';
    
    export class component1 implements OnInit {
    
    data: any;
    
    constructor (private service: Service) {}
    
    sendDataToService() {
         this.service.setData(this.data);
    }
    

    Component2.ts

    import { Service } from '../../service.service';
    
    export class component2 implements OnInit {
    
    constructor ( private service: Service ) { }
    
    ngOnInit() {
        this.service.currentData.subscribe(data => {
          console.log(data);
        });
    }
    

提交回复
热议问题