Search code examples
angulareventemitter

Default Value for Event Emitter


Suppose I have some event that emits a string value from a service:

public myString: EventEmitter<string> = new EventEmitter<string>();

And then in my component, I emit it as follows:

this.myService.myString.emit(value)

I want to set a default value for the string that consumes this event when no event has yet to be emitted. Is it possible to do something like:

public setString: string = 'Default Value, No Emission Yet' || this.myService.subscribe(emittedValue => this.setString = emittedValue);

Solution

  • Since you are using a service, I would recommend not to use EventEmitter: What is the proper use of an EventEmitter?

    Since you want an initial value, I would suggest a BehaviorSubject that takes an initial value.

    import { BehaviorSubject } from 'rxjs/BehaviorSubject';
    
    private myString = new BehaviorSubject<string>('Default Value, No Emission Yet')
    public myString$ = this.myString.asObsevable();
    

    Then just in your component you can listen to this observable and perform actions accordingly. Remember to unsubscribe when component is destroyed!

    mySub = new Subscription();
    
    constructor(private myService: MyService) { 
      this.mySub = myService.myString$.subscribe(value => {
        // conditions and do stuff...
      })
    }
    
    ngOnDestroy() {
      this.mySub.unsubscribe();
    }