当httpClient从构造器调用HTTPCLIENT时,角组件构造函数将加载两次
当HTTPClient函数从同一构造函数调用时,角构造函数将两次负载。
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.
}
}
是否建议从构造函数中进行API调用?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有第一次销毁的情况下两次加载组件的构造函数,因此我认为您的应用程序中有另一部分代码负责两次加载组件,无论如何我也尝试了一些修改的代码而且,这是正确的工作,没有您提到的问题
和您的问题,是的,在宁愿从服务中调用它的组件的API是一种不好的做法。我希望这对您有所帮助
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
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