In my Angular service, I retrieve data from the backend. Within this service, there is a variable of type ReplaySubject
that I subscribe to in my component
.
Current Code
@Injectable()
export class PersonService {
// The person subject
personStream: ReplaySubject<Person> = new ReplaySubject();
// Fetch person from DB and add to stream
getDataFromDB() {
this.http.get(url).subscribe(response => {
this.personStream.next(response.person);
});
}
}
@Component({...})
export class MyComponent implements OnInit {
person: Person;
constructor(private personService: PersonService) {}
ngOnInit() {
this.personService.personStream.subscribe(person => this.person = person);
}
}
The code above works as expected, but I've come across a different approach in another code snippet. Instead of subscribing directly to the ReplaySubject
, you can create a new function in the service of type Observable
and then subscribe to that function within the component.
Alternate Example
@Injectable()
export class PersonService {
// The person subject
personStream: ReplaySubject<Person> = new ReplaySubject();
// The person observable
person$(): Observable<Person> {
return this.personStream.asObservable();
}
// Fetch person from DB and add to stream
getDataFromDB() {
this.http.get(url).subscribe(response => {
this.personStream.next(response.person);
});
}
}
@Component({...})
export class MyComponent implements OnInit {
person: Person;
constructor(private personService: PersonService) {}
ngOnInit() {
// Subscribe to person observable. This will be triggered whenever the person data changes.
this.personService.person$().subscribe(person => this.person = person);
}
}
Both approaches work, but I am curious to know the most efficient way to handle this.
Thank you.