public

Angular 7 Observables: Who’s listening?

Figuring out who is listening to your output(s) sounds complicated but it’s pretty straight forward. Every Observable has a “observers” property which is an array of Subscriber’s.

Latest Post Svelte 5 tables proper. by Matthew Davis public

Figuring out who is listening to your output(s) sounds complicated but it’s pretty straight forward. Every Observable has a “observers” property which is an array of Subscriber’s.

Observable.observers

Observable.observers is just an array of Subjects:

@Component({
    selector: 'app-components-sharing-a',
    templateUrl: './components-sharing-a.component.html',
    styleUrls: [ './components-sharing-a.component.scss' ]
})
export class ComponentsSharingAComponent implements OnInit {

    @Output() public outputOne = new EventEmitter();

    public ngOnInit(): void {

        console.log('this.outputOne.observers.length: ' + this.outputOne.observers.length); 
        // output: this.outputOne.observers.length: 3

    }
    
    public isAnybodyListeningToMe(): boolean {
        
        return !!this.outputOne.observers.length;
        
    }

}

We can send a message directly to a specific observer with stream$.observers[0].next(event).

Component @Output()

Take the following component and see how you’re able to get the length of the observers array:

@Component({
    selector: 'app-components-sharing-a',
    templateUrl: './components-sharing-a.component.html',
    styleUrls: [ './components-sharing-a.component.scss' ]
})
export class ComponentsSharingAComponent implements OnInit {

    @Output() public outputOne = new EventEmitter();

    public ngOnInit(): void {

        console.log('this.outputOne.observers.length: ' + this.outputOne.observers.length);
        // outputs: this.outputOne.observers.length: 1

    }

}

See Also

Matthew Davis

Published 5 years ago