cooper
cooper

Reputation: 437

Unable to pass data between Angular 2 components using a shared service

I am passing info from a read component to an edit component. I used a shared service (modeled off of this post) but in the child component the Employee info is null. I think maybe I am unintentionally instantiating the service twice which is why it's empty (?) but not sure where I am doing this. The lines with //undefined should have the same employee info as the parent (parent is working)

Parent

@Component({
    providers: [EmployeesService]
})

export class EmployeeParentComponent {
    private employee: Employee;

    constructor(
        private employeesService: EmployeesService,
        protected router: Router,
        protected route: ActivatedRoute,) { }

    ngOnInit(): void {

    }
//called from HTML template on Edit button click
    toggleEditMode(employee: Employee) {
        this.employeesService.employee = employee;
        alert(this.employeesService.employee.firstName); //correct name
        this.router.navigate('/editPage')
    }
}

Child

@Component({
    providers: []
})

export class EditEmployeeComponent {
    constructor(
        private employeesService: EmployeesService
        ) {
        console.info(employeesService.employee); //undefined
    }

    ngOnInit(): void {
        console.info(this.employeesService.employee); //undefined
    }
}

Service

@Injectable()
export class EmployeesService {
    public employee: Employee;
}

Upvotes: 0

Views: 401

Answers (1)

Pengyy
Pengyy

Reputation: 38171

The reason is that service instance provided by specific component(you are doing right now) can not be accessed by another component.

If you want to use a service as a singleton, you should provide it at your @NgModule's providers array.

So just remove EmployeesService from provider array of EmployeeParentComponent and add it to your @NgModule's providers array

Upvotes: 3

Related Questions