简体   繁体   English

Angular 中的服务/API 调用

[英]Service/API calls in Angular

I had started learning angular.我已经开始学习 angular。 I observed that API calls are doing within the ngOnInit.我观察到 API 调用在 ngOnInit 中进行。 Why not inside the constructor as we are doing dependency Injection also there.为什么不在构造函数内部,因为我们也在那里进行依赖注入。 I know that component will be completely getting loaded inside the onInit function.我知道该组件将完全加载到 onInit function 中。 So, Is there any problem if we access/call api data in constructor before loading component, if so in which way it will be?那么,如果我们在加载组件之前在构造函数中访问/调用 api 数据有什么问题吗?

The constructor should be used for dependency injection and to create/init objects.构造函数应该用于依赖注入和创建/初始化对象。 It is JS engine calls constructor and not Angular.它是 JS 引擎调用构造函数,而不是 Angular。

The ngOnInit() method is a special lifecycle hook and give us a signal that Angular has finished initialising the component. ngOnInit() 方法是一个特殊的生命周期钩子,它给我们一个信号,表明 Angular 已经完成了组件的初始化。 ngOnInit() gives us a guarantee that bindings are available and allows you to invoke method calls. ngOnInit() 为我们提供了绑定可用的保证,并允许您调用方法调用。 It's a common practice to use ngOnInit to perform initialization logic even if this logic doesn't depend on dependency injection, DOM or input bindings.使用 ngOnInit 执行初始化逻辑是一种常见的做法,即使此逻辑不依赖于依赖注入、DOM 或输入绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM