简体   繁体   English

Angular 8:将 utils 服务定义为单例并使用静态方法?

[英]Angular 8: Define a utils service as singleton and with static methods?

I'm currently starting with Angular 8. Now I want to write a service containing util functions ("CoreService").我目前从 Angular 8 开始。现在我想编写一个包含 util 函数(“CoreService”)的服务。 But I'm wondering how exactly I should do that and what are the advantages or disadvantages of the different options:但我想知道我应该如何做到这一点以及不同选项的优缺点是什么:

  1. Should I define it as a singleton?我应该将其定义为单身人士吗?
  2. Should I define the functions as static methods (called by CoreService.doSomething() ) or should I define it as an injectable class with non-static methods (injected in constructor)?我应该将函数定义为静态方法(由CoreService.doSomething()调用)还是应该将其定义为具有非静态方法的可注入类(在构造函数中注入)?

Maybe one of the options has more or less impact on performance (memory?).也许其中一个选项对性能(内存?)有或多或少的影响。

Any answer is highly appreciated!任何答案都非常感谢!

Bye The_Unknown再见 The_Unknown

Okay, lets tackle down Services in Angular.好的,让我们解决 Angular 中的服务问题。 Let's get straight on some details first.让我们先了解一些细节。

The recommended way to create services is by using the CLI:创建服务的推荐方法是使用 CLI:

ng generate service foo/weather

This will create a new service under src/app/foo/weather.service.ts - along with some skeleton for your tests.这将在src/app/foo/weather.service.ts下创建一个新服务 - 以及一些测试框架。 If you inspect this code, you'd see that it looks something like this:如果你检查这段代码,你会发现它看起来像这样:

@Injectable({
  providedIn: 'root',
})
export class WeatherService {
  constructor() { }
}

1. Singleton or not 1. 单身与否

Now look above at the providedIn: 'root' line.现在看看上面的providedIn: 'root'行。 This way you are basically saying that Angular should provide this service at the root level.通过这种方式,您基本上是说 Angular 应该在根级别提供此服务。 In this case Angular will create a single, shared instance of your WeatherService and will inject this single instance into any component wanting it.在这种情况下,Angular 将创建 WeatherService 的单个共享实例,并将这个单个实例注入到任何需要它的组件中。 In addition, from the Angular documentation:此外,来自 Angular 文档:

Registering the provider in the @Injectable() metadata also allows Angular to optimize an app by removing the service from the compiled app if it isn't used.在 @Injectable() 元数据中注册提供者还允许 Angular 通过从编译的应用程序中删除未使用的服务来优化应用程序。

So this might also save you a bit of bandwidth.因此,这也可能为您节省一些带宽。

Of course services are there to be used by other components.当然,服务是由其他组件使用的。 If you decide to register a provider at the component level, you'll get a new instance of your service with each new instance of that component.如果您决定在组件级别注册一个提供程序,您将获得一个新的服务实例以及该组件的每个新实例。 It will be something like this:它会是这样的:

@Component({
  selector:    'app-cities',
  templateUrl: './cities.component.html',
  providers:  [ WeatherService ]
})

There is also a third "level" of granularity - scoped to a module - if you want to have an instance of your service available to all the components but just in the said module:还有第三个“级别”的粒度 - 范围为模块 - 如果您希望您的服务实例可用于所有组件,仅在所述模块中:

@NgModule({
  providers: [
    WeatherService,
    AnotherService
  ],
  ...
})

In a nutshell - you are in control of how you want to have your service - as a singleton or not - with all the implications.简而言之 - 您可以控制您希望如何获得服务 - 作为单身人士与否 - 以及所有影响。

2. Static or instance methods 2. 静态或实例方法

In my opinion this is not really a question.在我看来,这不是一个真正的问题。 The way to go is using instance methods.要走的路是使用实例方法。 This is anyway a bit enforced through the dependency injection of Angular.无论如何,这是通过 Angular 的依赖注入来强制执行的。 The components you will create will ask for an instance of your service.您将创建的组件将请求您的服务实例。 Angular's DI will provide one (singleton or a new one) and you can work with this one as with any other instantiated object: Angular 的 DI 将提供一个(单个或一个新的),您可以像处理任何其他实例化对象一样使用这个:

@Injectable({
  providedIn: 'root',
})
export class WeatherService {
  getTodaysTemperature() { return 7; }
}

@Component({
   ... // omitted for simplicity
})
export class TemperatureComponent {
  constructor(weatherService: WeatherService) {
      this.temperature = weatherService.getTodaysTemperature();
  }
}

So just make sure that you provide the corresponding instance methods and you are good to go.所以只要确保你提供了相应的实例方法就可以了。 Testing would also be fine as you can inject your service or even mock it.测试也可以,因为您可以注入服务甚至模拟它。

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

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