Angular2 - Interaction between components using a service

后端 未结 3 1257
谎友^
谎友^ 2020-11-29 09:12

I have two component A and B, where component A contains a button. I wish when user click on this button, fire a function on component B


         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 09:38

    Shared service is a common way of communication between non-related components. Your components need to use a single instance of the service, so make sure it's provided at the root level.

    An example using the BehaviorSubject as a data delegate:

    Shared service:

    @Injectable()
    export class SharedService {
    
        isVisibleSource: BehaviorSubject = new BehaviorSubject(false);
    
        constructor() { }
    }
    

    Component 1:

    export class Component1 {
    
        isVisible: boolean = false;
    
        constructor(private sharedService: SharedService) { }
    
        onClick(): void {
            this.isVisible = !this.isVisible;
            this.sharedService.isVisibleSource.next(this.isVisible);
        }
    }
    

    Component 2:

    export class Component2 {
    
        constructor(private sharedService: SharedService) { }
    
        ngOnInit() {
            this.sharedService.isVisibleSource.subscribe((isVisible: boolean) => {
                console.log('isVisible: ', isVisible); // => true/false
            });
        }
    }
    

    It is worth mentioning that BehaviorSubject upon a subscription returns the last value it holds, therefore the component from the example above will be updated with the most recent value immediately after the instantiation.

    BehaviorSubject also allows to get its most recent value without even subscribing to it:

    this.sharedService.isVisibleSource.getValue(); // => true/false
    

提交回复
热议问题