I am stuck on setting up change detection within the service layer for multiple components. Below I will just show one component to illustrate the subscribe on the behavior subject. I am not getting any errors, just no data is displaying. The http request is valid. I had this working with just two way data binding but I need the ability to update multiple components throughout the project. I thought that behavior subject might be the best choice but I could be wrong here. I really don't know/understand what I am doing wrong. Thank you in advice for any help.
The issue is within the getProjects() function. With the subscribe to the get request the result or error is never called before the view displays.
@Injectable()
export class ProjectService {
private projectsUrl: string = Globals.url + '/projects';
private getProjectsSource = new BehaviorSubject<any>([]);
getProjectsChange = this.getProjectsSource.asObservable();
private errorSource = new BehaviorSubject<any>({});
errorChange = this.errorSource.asObservable;
private projects: Project[] = [];
constructor(private http: Http) { }
getProjects() {
if (this.projects != null) {
this.getProjectsSource.next(this.projects);
}
else {
this.http.get(this.projectsUrl, Globals.getTokenHeaders())
.map(function (res) {
let data = res.json();
if (data) {
for (let project of data.projects) {
this.projects.push(Project.create(project));
}
return this.projects;
}
})
.catch((error: any) => Observable.throw(error || 'Server error'))
.subscribe(
result => {
this.projects = result;
this.getProjectsSource.next(this.projects);
},
error => {
this.errorSource.next(true);
});
}
}
}
This is the component which subscribes to the behavior subject setup in the service. I call the getProjects() method of the service within the constructor to trigger a change on component construction. I subscribe to it within the ngOnIt function.
@Component({
selector: 'app-nav-bar',
templateUrl: './nav-bar.component.html'
})
export class NavBarComponent implements OnInit {
projects: Project[] = [];
projectsFlag: boolean = false;
constructor(private projectService: ProjectService) {
this.projectService.getProjects();
}
ngOnInit() {
this.projectService.getProjectsChange.subscribe(result => {
this.projects = result;
},
err => {
// handle error in template through flag (need to setup flag)
});
}
}
EDIT: I fetch all the projects once but crud ops such as update or delete are both updated in the cache and on the server. So when an update to a project occurs it needs to update every component that is a subscriber to a particular observable which in this case I'm using behavior subject.