Angular> 2 Theme to subscribe directly or use method?

I have a service with a Subject member. The object provides an instance of the class:

public selectedProjectSubject: Subject<Project> = new Subject();

      

The Subject value is updated using the method:

public updateSelectedProject(project: Project) {
    this.selectedProjectSubject.next(project);
  }

      

In several classes, I subscribe to a topic:

this.projectSubscription = this.projectService.selectedProjectSubject.subscribe((project: Project) => {
      this.projectSelected = project;
    });

      

Is it okay to subscribe directly to the Subject or provide the Subject (Observable) in another way?

+3


source to share


1 answer


I use BehaviorSubject

in several places and I want my teammates not to use .value

outside of the service containing the object, so I usually do the following for all items:

private _selectedProject = new Subject<Project>();
get selectedProject(): Observable<Project> {
  return this._selectedProject;
}

      



However, there really aren't as many problems accessing it as you have, and you can always change my approach later if you need to, without even refactoring any of the callers, just using an get

accessor.

0


source







All Articles