Reputation: 1145
This is my theoretical service:
@Injectable({
providedIn: 'root'
})
export class DataService {
@Output() data: EventEmitter<number> = new EventEmitter();
constructor() {
setInterval(() => {
this.data.emit(Math.random());
}, 1e3);
}
}
And my component:
ngOnInit() {
this.sub = this.dataService.data.subscribe(data => this.data = data);
}
ngOnDestroy() {
this.sub.unsubscribe();
}
Works good, I have new data when it comes. But how to change my DataService to provide data immediately after subscription. I mean, I want to store last data (in this theoretical case random number) and provide it right after subscription. Is this even possible using rxjs?
Upvotes: 1
Views: 202
Reputation: 29335
don't use event emitters in place of subjects, they are not guaranteed to always follow the observable contract
don't use an output in a service, it applies to components and directives only
use a behavior subject to have new subscribers immediately get the last emitted value upon subscription
good practice to make subjects private and expose a public observable
Like so:
@Injectable({
providedIn: 'root'
})
export class DataService {
private data: BehaviorSubject<number> = new BehaviorSubject(null); // initialize to whatever
data$: Observable<number> = this.data.asObservable();
constructor() {
setInterval(() => {
this.data.next(Math.random()); // use next for subjects
}, 1e3);
}
}
Upvotes: 3