Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to call HTTP endpoints in an Angular service constructor? [closed]

Tags:

angular

In the Angular documentation, there is the following tip about code in a component constructor (second paragraph emphasized by me):

Call it in ngOnInit

While you could call getHeroes() in the constructor, that's not the best practice.

Reserve the constructor for simple initialization such as wiring constructor parameters to properties. The constructor shouldn't do anything. It certainly shouldn't call a function that makes HTTP requests to a remote server as a real data service would.

Instead, call getHeroes() inside the ngOnInit lifecycle hook and let Angular call ngOnInit at an appropriate time after constructing a HeroesComponent instance.

What about for services? Is it also bad to have an HTTP call (just the launch of an async request where the Observable is stored locally) in the constructor? Services don't have an ngOnInit() event, so what would the best practice for Services be?

like image 295
Daniel Gray Avatar asked May 04 '18 13:05

Daniel Gray


People also ask

What goes in the constructor in angular?

Constructor in Angular is put into use to inject dependencies into the component class. It creates a new instance of the class when the compiler calls 'new MyClass ()'. While calling 'new MyClass()', it is vital that the exact match of the parameter passes the Angular component constructor of the class.

Is constructor required in angular?

The constructor is a method in JavaScript and is considered as a feature of the class in es6 . When the class is instantiated it immediately runs the constructor whether it is used in Angular framework or not.So it is called by JavaScript engine and Angular has no control on that.

What is HTTP request in angular?

HttpRequest represents an outgoing request, including URL, method, headers, body, and other request configuration options. Instances should be assumed to be immutable. To modify a HttpRequest , the clone method should be used.


1 Answers

I bet that you can find some examples of where constructor can be used with no harm but as a rule of thumb and best practice use "angular constructor" for it aka ngOnInit lifecycle hook.

Sometimes using constructor can be impossible or requires additional work. For example, you need to fetch data from backend using service because if @Input() data. Inputs are not bound during javascript object construction, but they are available in ngOnInit

Moreover what if you want to unit test your component/service? You create new instance for every test (thus invoking a constructor) and you are making additional calls to mocked http backend, or even worst - to live one.

like image 171
Antoniossss Avatar answered Sep 28 '22 06:09

Antoniossss