angular - 如何将带有参数化构造函数的服务注入(inject)组件 - Angular

标签 angular dependency-injection

创建一个服务类(CourseService):

具有参数化构造函数的服务类

 import { Injectable } from '@angular/core';

  @Injectable()
  export class CourseService {

  constructor(private name?:string) { }

  getName() : string{
    return "Service Name is"+ this.name;
  }

}

将服务注入(inject)组件。

在提供者中,它已经像这样注入(inject)了
  providers: [
    CourseService
  ]

创建组件类
    import { Component, OnInit } from '@angular/core';
    import { CourseService } from '../../services/course.service';

    @Component({
      selector: 'app-course',
      templateUrl: './course.component.html',
      styleUrls: ['./course.component.css']
    })
    export class CourseComponent implements OnInit {

      constructor(private courseService: CourseService) { }

      ngOnInit() {

        let serviceName = this.courseService.getName();
      }

    }

浏览器控制台错误:
 AppComponent.html:1 ERROR Error: StaticInjectorError[CourseService]: 
   StaticInjectorError[CourseService]: 
   NullInjectorError: No provider for CourseService!
   at _NullInjector.get (core.js:993)
   at resolveToken (core.js:1281)
   at tryResolveToken (core.js:1223)
   at StaticInjector.get (core.js:1094)
   at resolveToken (core.js:1281)
   at tryResolveToken (core.js:1223)
   at StaticInjector.get (core.js:1094)
   at resolveNgModuleDep (core.js:10878)
   at NgModuleRef_.get (core.js:12110)
   at resolveDep (core.js:12608)

如何在组件中注入(inject)此服务?

最佳答案

这是设计上不可能的。 Angular 的可注入(inject)对象在定义服务的整个范围内共享(只有一个实例)。在构造函数中为同一个实例传递不同的参数是没有意义的。如果您需要许多服务实例,您可以自己创建它,只需执行以下操作:

export class CourseComponent implements OnInit {
  private courseService: CourseService;
  constructor() { 
    this.courseService = new CourseService('someName');
  }

  ngOnInit() {
    let serviceName = this.courseService.getName();
  }
}

关于angular - 如何将带有参数化构造函数的服务注入(inject)组件 - Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47823369/

相关文章:

java - Guice - 如何创建一个没有参数构造函数单例的类并让变量自动注入(inject)?

c# - 具有多个存储库和服务的 .NET MVC Controller ?

java - Guice 使用不同的提供者实例化不同的类

Angular 2 : Load different versions of the libraries based on the data

angular 2 在 index.html 中引用外部 js 文件

javascript - 头上有重复的样式和很多 <style> 元素

php - 如何处理具有多个依赖项的函数

带有primeng 7 或Angular 2+ 的angular-fontawesome 5 图标

javascript - 导入一个没有 Angular 6 路径的模块

angular - 如何在父类中注入(inject)服务而不在构造函数中传递服务? Angular 6