简体   繁体   English

Angular:使用构造函数注入服务的替代方法

[英]Angular: alternative to injecting services using the constructor

All examples I found, injected a service like this:我发现的所有示例都注入了这样的服务:

export class TestComponent {

  constructor(
    private dataService: DataService,
    private dataService2: DataService2,
    private dataService3: DataService3,
    // ...
    // ...
    // ...
    // ...
    // ...
    // ...
    // ...
  ) {
        // Do something
    }
}

However, this list can get very long and confusing if you inject several services and also use the constructor method to initialize something.但是,如果您注入多个服务并使用构造函数方法来初始化某些内容,则此列表可能会变得很长且令人困惑。 So the question is:所以问题是:
Can I write this alternatively?我可以写这个吗?

export class TestComponent {

  private dataService = new DataService();
  private dataService2 = new DataService2();
  private dataService3 = new DataService3();

  constructor() {
        // Do something
  }
}

It depends on what exactly your service need to do.这取决于您的服务究竟需要做什么。 If it just a bunch of usefull methods, you can do it, but in every component where u write somthing like this private dataService = new DataService();如果它只是一堆有用的方法,你可以做到,但是在你编写类似private dataService = new DataService();这样的东西的每个组件中private dataService = new DataService(); u will get new instance of service.你会得到新的服务实例。

on the other hand, in my work we often use Services as data storages, to query something from it, with this new keyword u will instantiate it and won't get any data that were passed from another component.另一方面,在我的工作中,我们经常使用服务作为数据存储,从中查询某些内容,使用这个new关键字,您将实例化它并且不会获取从另一个组件传递的任何数据。

Anyways DI is a great part of Angular ecosystem.无论如何,DI 是 Angular 生态系统的重要组成部分。 So u can declare it into providers on modules (before that separate your components to rely on some module) that are actually using them to lower its quantity into app module.因此,您可以将其声明为模块上的提供程序(在此之前将您的组件分开以依赖某个模块),这些模块实际上正在使用它们将其数量降低到应用程序模块中。 Because if you inject som many stuff into 1 component constructor better to separate some functionality, because it may become really ugly.因为如果您将许多东西注入 1 个组件构造函数中以更好地分离某些功能,因为它可能变得非常丑陋。

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

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