简体   繁体   English

Angular 2+:在构造函数调用中注入服务有困难

[英]Angular 2+: Difficulty in injecting services in constructor calls

I'm migrating the codebase of https://github.com/oppia/oppia from AngularJS to Angular 2+.我正在将https://github.com/oppia/oppia的代码库从 AngularJS 迁移到 Angular 2+。 We have a lot of services, about 300+.我们有很多服务,大约 300 多个。 I migrated a filter normalize-whitespace to Angular 2+.我将过滤器归一化空白迁移到 Angular 2+。 Now, I was migrating the service Validator Service which uses this filter.现在,我正在迁移使用此过滤器的服务验证器服务

import { AlertsService } from 'services/AlertsService';
import { AppConstants } from 'app.constants';
import { NormalizeWhitespacePipe } from
  'filters/string-utility-filters/normalize-whitespace.pipe.ts';
import { UtilsService } from 'services/UtilsService.ts';

import { Injectable } from '@angular/core';
import { downgradeInjectable } from '@angular/upgrade/static';

@Injectable({
  providedIn: 'root'
})
export class ValidatorsService {
  private normalizeWhitespace: NormalizeWhitespacePipe = (
    new NormalizeWhitespacePipe(new UtilsService()));
  constructor(private alertsService: AlertsService) {}

This is the starting part of the Validator Service.这是验证器服务的起始部分。 The Normalize WhiteSpace filter depends on UtilsService and hence I need to pass that as a constructor argument since its injected in the filter. Normalize WhiteSpace 过滤器依赖于 UtilsService,因此我需要将它作为构造函数参数传递,因为它被注入过滤器。 The question is if UtilsService too depends on other services say A and B, and A depends on others services and so on, don't you think the initialisation of normalizeWhitespace would be too difficult!问题是如果 UtilsService 也依赖于其他服务,比如 A 和 B,而 A 依赖于其他服务等等,你不觉得normalizeWhitespace的初始化太难了吗!

Is there any solution to this problem?这个问题有什么解决办法吗?

Thanks!谢谢!

You don't need to do this你不需要这样做

  private normalizeWhitespace: NormalizeWhitespacePipe = (
    new NormalizeWhitespacePipe(new UtilsService()));

in order to initialize a service.为了初始化服务。

It's quite simple: you just need to declare all the dependencies always in the constructor (as you are doing with AlertsService ), then angular will inject to each service what is needed based on that .这很简单:您只需要始终在构造函数中声明所有依赖项(就像您对AlertsService所做的那样),然后angular 将根据该向每个服务注入所需的内容

Just make sure that all the services that should be globally available are provided in the root app.module, as you are doing with ValidatorsServices with只需确保在根 app.module 中提供了所有应该全局可用的服务,就像您对 ValidatorsServices 所做的那样

@Injectable({
  providedIn: 'root'
})

Here's the official documentation .这是官方文档

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

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