组件构造函数中的依赖注入

时间:2020-05-03 17:46:45

标签: angular

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

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

这与依赖注入和创建服务有关。

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

如前所述,依赖项注入可以通过以下方式在给定组件的构造函数中发生:

constructor(private counterService: CounterService) {}

但是在另一种情况下,它导致了错误(此构造函数与角度依赖性注入不兼容),我需要在Google上搜索并找到此方法:

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);
  }
}

1 个答案:

答案 0 :(得分:1)

对于Angular 9,默认情况下使用新的编译器和运行时指令,而不是旧的编译器View Engine。因此,在角度中添加了以下要求。

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

在角度9之前,您编写的内容有效。但是现在,userService有一个counterService的引用,该引用又被注入到组件中。所以@Inject是必需的,因为计数器服务未添加@Injectable。

除非将其他服务扩展到其他服务中,否则将服务注入到其他服务中就没有此要求。

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

由于v8仍然很流行,您可以检查此链接以了解团队在迁移期间建议的问题和修复。