I'm trying to share data between sibling components (The component below is in a for loop, in the view).
I've set up a service, so that I can store a variable, that these sibling components can access. The problem is when I try to access a value from the service, via a component method, it comes back as undefined. I can pass a number into the service and update it, but when I try to retrieve it, I can't do it.
What's interesting is that if you console log the service value in the constructor, it will retrieve something.
Can anybody help with this? I've tried to follow Max's Service chapter as best as I can, but I don't seem to be getting anything.
Service
export class ProjectTaskDataService {
currentTaskId = 0;
logTaskSelectionChange(selected_task_id: number) {
this.currentTaskId = selected_task_id;
}
public getSelectedTaskId() {
return this.currentTaskId;
}
}
Component
import { Component, OnInit, Input } from '@angular/core';
import {ProjectTaskDataService} from '../../../../services/project-task-data.service';
@Component({
selector: '[app-section-tasks]',
templateUrl: './section-tasks.component.html',
styleUrls: ['./section-tasks.component.css'],
providers: [ProjectTaskDataService]
})
export class SectionTasksComponent implements OnInit {
@Input() taskItemData: {id: number, name: string, date: string, type: string, status: string}
taskId: number;
taskName: string;
taskDate: string;
taskType: string;
taskStatus: string;
taskSelected = false;
// This is the value that stores the ID for the current selected task for the section...
sectionSelectedTaskId: number;
constructor(private projectTaskDataService: ProjectTaskDataService) { }
ngOnInit() {
// console.log(this.taskItemData);
this.taskId = this.taskItemData.id;
this.taskName = this.taskItemData.name;
this.taskDate = this.taskItemData.date;
this.taskType = this.taskItemData.type;
this.taskStatus = this.taskItemData.status;
// Returns 0, if called here
console.log(this.projectTaskDataService.currentTaskId);
}
selectTask(id: number) {
// This will return 'undefined'
console.log('Distraction ', this.projectTaskDataService.getSelectedTaskId());
this.projectTaskDataService.logTaskSelectionChange(id);
this.sectionSelectedTaskId = this.projectTaskDataService.currentTaskId;
}
The problem is here:
providers: [ProjectTaskDataService]
By registering the service in the component's providers array, the instance of the component is only shared with this component and its children.
To share the service between sibling components, register it instead in a module's providers array.
Or better yet, if you are using Angular 6 or higher, use the new providedIn
registration technique for the service:
@Injectable({
providedIn: 'root'
})
export class MyService {
}
This registers the service with the application's root injector, and the service instance is then shared between all of the components of the application.