8

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);
User 5842
  • 2,849
  • 7
  • 33
  • 51

1 Answers1

7

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();
}
AT82
  • 71,416
  • 24
  • 140
  • 167