[英]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. 我使用了共享服务( 以本文为蓝本 ),但是在子组件中,Employee信息为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;
}
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. 如果要将服务用作单例,则应在@NgModule
的providers数组中提供它。
So just remove EmployeesService
from provider array of EmployeeParentComponent
and add it to your @NgModule
's providers array 所以只要删除EmployeesService
从供应商阵列EmployeeParentComponent
并将其添加到您的@NgModule
的供应商阵列
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.