Angular Component constructor loads twice when httpClient is called from Constructor

188 views Asked by At

Angular constructor loads twice when httpClient functions are called from the same constructor.

       export class ViewOrderDetailsComponent {
            constructor(
                   private activatedRoute: ActivatedRoute,
                   private router: Router,
                   private httpClient:HttpClient) {
        console.log("_______________constructor____________");   
    this.httpClient.get("https://jsonplaceholder.typicode.com/todos/1",{headers: null, params:null}).subscribe();
   //constructor loads once if above line is commented.
           
                }
        }

Is it not suggested to make api call from constructor?

1

There are 1 answers

0
Mahdoui Hafedh On

there is no way to loads constructor of component twice without destroy it first so i think there is another part of code in your application is responsible to load your component twice, anyway i also tried your code with some modification because headers and params connot be null and it's work properly without the problem you mention

this.httpClient.get("https://jsonplaceholder.typicode.com/todos",{headers:new HttpHeaders,params:{id:5,completed:false}}).subscribe(data=>{
  console.log(data);
});

and about your question,yes is a bad practice to call api in constructor of a component it prefer to call it from service.i hope that's help you somehow