【问题标题】:Dependency injection in component's constructor组件构造函数中的依赖注入
【发布时间】:2020-05-04 02:36:16
【问题描述】:

我是 Angular 的新手,目前正在做一个教程来学习它。

我遇到了一个问题,我想知道是否有人可以帮我看清楚。

这是关于依赖注入和创建服务的。

作为一个练习,我需要创建两个服务并将它们注入到另一个组件中以使它们可用。

正如所教导的,依赖注入可以通过以下方式在给定组件的构造器中发生:

constructor(private counterService: CounterService) {}

但在另一种情况下它导致了错误(这个构造函数与角度依赖注入不兼容),我需要谷歌它并找到这个方法:

constructor(@Inject(UserService) private userService) {}

谁能解释一下,两者有什么区别?这两个服务位于相同的文件夹结构中。我有 Angular 版本 9。

谢谢!


export class CounterService  {
  inactiveToActiveCount: number = 0;
  activeToInactiveCount: number = 0;

  increaseActiveToInactiveCounter() {
    this.activeToInactiveCount = this.activeToInactiveCount +1;
    console.log("Active to inactive: " + this.activeToInactiveCount);
  }

  increaseInactiveToActiveCounter() {
    this.inactiveToActiveCount = this.inactiveToActiveCount +1;
    console.log("Inactive to active: " + this.inactiveToActiveCount);
  }

}

import { Injectable } from '@angular/core';
import { CounterService } from './counter.service';

@Injectable()
export class UserService {
  activeUsers = ['Max', 'Anna'];
  inactiveUsers = ['Chris', 'Manu'];

  constructor(private counterService: CounterService) {
    //
  }

  setToInactive(id: number) {
      this.inactiveUsers.push(this.activeUsers[id]);
      this.activeUsers.splice(id, 1);
      this.counterService.increaseActiveToInactiveCounter();
  }

  setToActive(id: number) {
      this.activeUsers.push(this.inactiveUsers[id]);
      this.inactiveUsers.splice(id, 1);
      this.counterService.increaseInactiveToActiveCounter();
  }
}

我在这个组件中使用它们:

import { Component, OnInit, Inject } from '@angular/core';
import { UserService } from '../common/user.service';

@Component({
  selector: 'app-active-users',
  templateUrl: './active-users.component.html',
  styleUrls: ['./active-users.component.css']
})
export class ActiveUsersComponent implements OnInit {
  users: string[];

  constructor(@Inject(UserService) private userService) {
    //
  }

  ngOnInit() {
    this.users = this.userService.activeUsers;
  }

  onSetToInactive(id: number) {
    this.userService.setToInactive(id);
  }
}

【问题讨论】:

  • 在 angular9 中,所有使用依赖注入的类都必须有一个 Angular 类级别的装饰器 @Injectable()。
  • 能否也分享一下您的userservice和counterservice?
  • @ArunMohan 我编辑了我的帖子

标签: angular


【解决方案1】:

在 Angular 9 中,默认使用新的编译器和运行时指令,而不是旧的编译器视图引擎。正因为如此,在angular中添加了以下要求。

将@Injectable 装饰器添加到您计划提供的任何内容或 注入。

在 Angular 9 之前,您写的内容是有效的。但是现在, userService 有一个 counterService 的引用,它又被注入到组件中。所以@Inject 是必需的,因为柜台服务没有添加@Injectable。

将服务注入另一个服务没有这个要求,除非你是从另一个服务扩展而来的。

https://angular.io/guide/ivy-compatibility-examples

您可以查看此链接以了解团队在迁移期间建议的问题和修复,因为 v8 仍然很受欢迎。

【讨论】:

  • 感谢您的快速帮助!
猜你喜欢
  • 2011-02-02
  • 2018-06-17
  • 2018-01-17
  • 1970-01-01
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多