Share object between 2 child components

后端 未结 2 2088
情话喂你
情话喂你 2021-02-11 08:12

I have a main component with 3 sub-components.

Main component HTML structure looks like this:

2条回答
  •  清歌不尽
    2021-02-11 08:28

    @Input API can be used when you have parent-child scenario and sending data from parent to child. But here, you are having sibling components. EventEmitter can be used but over the time it becomes complex.
    I'd suggest to use sharedService with subject from Rxjs library.

    NOTE: Please bear with Naming Convention for this example.

    https://plnkr.co/edit/7A21ofKNdi0uvbMgLUDZ?p=preview

    sharedService.ts (with subject)

    import {Injectable} from 'angular2/core';
    import { Subject }    from 'rxjs/Subject';
    
    @Injectable()
    export class sharedService {
    
        private parkingType = new Subject();
        parkingType$ = this.parkingType.asObservable();
    
        ParkingType(jsonData){
         console.log(jsonData);
          this.parkingType.next(jsonData);
        }
    
    } 
    

    availableParking.ts

    import {Component} from 'angular2/core';
    import {sharedService} from 'src/sharedService';
    
    @Component({
      selector: 'navbar',
      template: `
       

    Available parking

    ` }) export class availableParking{ myjson=[{"parkingType":"free parking"},{"parkingType":"paid parking"}]; constructor(private ss: sharedService) {} send() { console.log(this.myjson); this.ss.ParkingType(this.myjson); } }

    reservedParking.ts

    import {Component,Injectable} from 'angular2/core';
    import {sharedService} from 'src/sharedService';
    import {someService} from 'src/someService';
    import 'rxjs/Rx';
    @Component({
      selector: 'thecontent',
        template: `
        

    Reserved parking

    {{myjson|json}} ` }) export class reservedParking{ myjson:string[]; constructor(private ss: sharedService) { ss.parkingType$.subscribe((res)=>this.myjson=res); } }

提交回复
热议问题