当httpClient从构造器调用HTTPCLIENT时,角组件构造函数将加载两次

发布于 2025-01-22 05:26:16 字数 596 浏览 4 评论 0原文

当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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨轻弹 2025-01-29 05:26:17

没有第一次销毁的情况下两次加载组件的构造函数,因此我认为您的应用程序中有另一部分代码负责两次加载组件,无论如何我也尝试了一些修改的代码而且,这是正确的工作,没有您提到的问题

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

和您的问题,是的,在宁愿从服务中调用它的组件的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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文