简体   繁体   English

在Angular 2中调用服务的最佳方法是什么

[英]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.

相关问题 在角度服务中处理来自后端api的数据的最佳方法是什么? - What is the best way to work with data from a backend api in an angular service? 在角度2(Beta)中将一项服务注入另一项服务的最佳方法是什么? - What's the best way to inject one service into another in angular 2 (Beta)? 在Angular服务中取消订阅无限可观察量的最佳方法是什么? - What is the best way to unsubscribe infinite observables in an Angular service 基于Angular 2中的环境调用模块的最佳方法是什么 - What is the best way to call module based on the environment in Angular 2 将 angular 6 升级到 9 的最佳方法是什么? - What is the best way to upgrade angular 6 to 9? 避免 Angular 组件中的许多 if 语句调用特定函数的最佳方法是什么? - What's the best way to avoid many if statements in Angular component to call specific function? 在角度2的http调用之后返回热/共享可观察量的最佳方法是什么 - What is the best way to return a hot/shared observable after a http call in angular 2 以编程方式将类型传递给服务的最佳方法是什么? - what is the best way to programmatically pass a type to a service? 在订阅中调用订阅的最佳方式是什么? - What is the best way to call subscribe inside a subscribe? 有没有办法成功循环 Angular 服务调用 - Is there a way to successfully loop an Angular service call
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM