简体   繁体   English

我应该在其构造函数中还是在 app.component 的 ngOnInit 方法中初始化 Angular 服务?

[英]Should I initialise an Angular service in its constructor or in the ngOnInit method of the app.component?

I'm new to Angular.我是 Angular 的新手。 I have a service that needs to subscribe to a subject provided by another service.我有一项服务需要订阅另一个服务提供的主题。 If this was a component, I would create the subscription in the ngOnInit method of the component.如果这是一个组件,我会在组件的 ngOnInit 方法中创建订阅。 NgOnInit isn't called for Services, though.不过,服务不需要 NgOnInit。 I have created an initialise method to create the subscription but I'm not sure where best to call it from.我创建了一个初始化方法来创建订阅,但我不确定从哪里最好地调用它。 I have seen it done two ways:我已经看到它以两种方式完成:

1) Call the initialise method in the service constructor 1)在服务构造函数中调用initialise方法

2) Inject the service into the app.component and call the service initialise method in the app.component's ngOnInit method eg 2)将服务注入到app.component中,并在app.component的ngOnInit方法中调用服务初始化方法,例如

method 1:方法一:

export class MyService{

    constructor(private myRequiredService: RequiredService) {
        this.initialiseSubs();
    }

    initaliseSubs(){
        //code to set up subscriptions
    }
}

Method 2方法二


export class MyService{

    constructor(private myRequiredService: RequiredService) {}

    initaliseSubs(){
        //code to set up subscriptions
    }
}

export class AppComponent implements OnInit{
  title = 'my-app';

  constructor(private myService:MyService){}

  ngOnInit(){
    this.myService.initialiseSubs();

  }
}

Both methods seem to work but I would welcome advice as to which is preferable.两种方法似乎都有效,但我欢迎就哪种方法更可取提出建议。 Thanks in advance.提前致谢。

The service is the place where you define your observables, for example, getAllEmployees() , The components are the place where you use those services ( inject the service into the constructor).服务是您定义可观察对象的地方,例如getAllEmployees() ,组件是您使用这些服务的地方(将服务注入构造函数)。

    export class MyService{
    
        constructor(private myRequiredService: RequiredService) {}
    
        getAllEmployees():Observable<Employee[]>{
           
           // return Observables of type Employee[]
        }
    }

Suppose now you have a component called EmployeesList that's responsible for showing all the employees data, first, you need to inject the service into the constructor, then you need to call the getAllEmployees service method and subscribe in order to get the data.假设现在您有一个名为EmployeesList的组件,它负责显示所有员工数据,首先,您需要将服务注入到构造函数中,然后您需要调用getAllEmployees服务方法并订阅以获取数据。

    export class EmployeesListimplements OnInit{
      private employees: Employee[];
    
      constructor(private myService:MyService){}
    
      ngOnInit(){
         // it's better to do the subscription inside ngOnInit.
        this.myService.getAllEmployees().subscribe(
          employees => {
             this.employees = employees; 
          }

        );
  
      }
    }

That's basically how you should do it, but for better development and better user experience I advice using angular resolvers , resolvers are basically methods that can be attached to a specific route and angular will call them before rendering the component, inside these methods you need to subscribe to the getAllEmployees service method and get the values inside the component, the main goal of using resolvers is to avoid rendering the view then waiting for the data to be fetched from the resources.基本上你应该这样做,但为了更好的开发和更好的用户体验,我建议使用angular resolvers ,解析器基本上是可以附加到特定路由的方法,angular 将在渲染组件之前调用它们,在这些方法中你需要订阅getAllEmployees服务方法并获取组件内部的值,使用解析器的主要目的是避免渲染视图然后等待从资源中获取数据。
But that's considered as an advanced topic, I will not post any codes for that unless you asked me for.但这被认为是一个高级主题,除非您要求我,否则我不会为此发布任何代码。

Please mark it as correct if the answer did help you.如果答案对您有帮助,请将其标记为正确。 All the best!一切顺利!

Edit After discussing below in the comments, I understood that you have different back-ends to communicate with depending on the current route, I would handle this case just like this:编辑在下面的评论中讨论后,我了解到您有不同的后端可以根据当前路由进行通信,我会像这样处理这种情况:

    // inside the component 
    constructor(private router: Router) {}
    ngOnInit(){
            // You need to find 
            this.myService.getAllEmployees(this.router.url).subscribe(
              employees => {
                 this.employees = employees; 
              }
    
            );
      
    }

// inside the service file:

    export class MyService{
        
            constructor(private myRequiredService: RequiredService) {}
        
            getAllEmployees(URL: string):Observable<Employee[]>{
               // decide which back-end to connect with depending on the URL
               switch(url){
                case "example1":
                                URL = "url1";
                         break;
                case "example2":
                                URL = "url2";
                         break;
               }
               // Connect to the resource using URL param
               // return Observables of type Employee[]
            }
    }

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

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