在 ngInit 中调用 angular 2 应用程序中的服务
Calling a service in angular 2 application in ngInit
我在 angular 2 中对调用服务进行了澄清。考虑以下程序:
@Component({
providers : [EmployeeService]
})
export class Employee implements OnInit {
employees : IEmployee[];
constructor(private _employeeService: EmployeeService)
{
}
ngOnInit()
{
this.employees = this._employeeService.getEmployees();
}
}
为什么我们有需要在 ngOnInit 中调用服务的经验法则,通常在任何其他编程语言中,我们只会为函数中的数据调用服务当我们需要时。
但在这里,即使我们可能需要也可能不需要,数据已经从服务中获取。为什么会这样?
如果您了解 angular 生命周期钩子 ngOnInit
它会被调用
创建组件后不久:
如果您最初需要在模板中显示一些数据,则获取数据的服务放在 ngOnInit
中
我在 angular 2 中对调用服务进行了澄清。考虑以下程序:
@Component({
providers : [EmployeeService]
})
export class Employee implements OnInit {
employees : IEmployee[];
constructor(private _employeeService: EmployeeService)
{
}
ngOnInit()
{
this.employees = this._employeeService.getEmployees();
}
}
为什么我们有需要在 ngOnInit 中调用服务的经验法则,通常在任何其他编程语言中,我们只会为函数中的数据调用服务当我们需要时。
但在这里,即使我们可能需要也可能不需要,数据已经从服务中获取。为什么会这样?
如果您了解 angular 生命周期钩子 ngOnInit
它会被调用
创建组件后不久:
如果您最初需要在模板中显示一些数据,则获取数据的服务放在 ngOnInit