[英]What is the best way to call a service in Angular 2
I am using angular 2 for fetching data from an API with an Injectable service written for it.Should I call my service in the constructor or ngoninit in the component where i am going to utilize my data. 我正在使用angular 2通过为其编写了Injectable服务的API从API中获取数据。应该在构造函数中调用我的服务,还是在组件中要使用我的数据的ngoninit中调用我的服务。 Can someone explain the best way to use constructor and ngoninit hook in angular 2 like constructor is used for instantiating services.
有人可以解释使用构造函数和角度2中的ngoninit钩子的最佳方法,例如构造函数用于实例化服务。
In my opinion you should call it in ngOnInit. 我认为您应该在ngOnInit中调用它。 First of all you have access to @Input's which is usually the case with services calling some api by http.
首先,您可以访问@Input,这通常是服务通过http调用某些api的情况。
In terms of designs, constructor should only assign dependencies. 就设计而言,构造函数应仅分配依赖项。 There shouldn't be any logic inside.
内部不应有任何逻辑。 It increase testibility of a class as you don't have to set up additional stuff on object creation.
它增加了类的可测试性,因为您不必在对象创建上设置其他内容。
The recommend way is defining the service in the constructor and call it in ngOnInit, for example: 推荐的方法是在构造函数中定义服务,然后在ngOnInit中调用它,例如:
constructor(private newsService: NewsService) {}
ngOnInit() {
this.newsService.method().....
}
Reference to: enter link description here 参考: 在此处输入链接描述
We use ngOnInit
for all the initialization/deceleration and avoid stuff to work in the constructor
. 我们将
ngOnInit
用于所有初始化/减速,并避免在constructor
工作。 The constructor
should only be used to initialize class members but shouldn't do actual "work". constructor
应仅用于初始化类成员,而不应执行实际的“工作”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.