简体   繁体   中英

How to Inject a Service with Parameterized constructor to a Component - Angular

Create a Service class (CourseService):

Service class with Parameterized constructor

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

  @Injectable()
  export class CourseService {

  constructor(private name?:string) { }

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

}

Injecting the service to Component.

In Provider its already injected like this

  providers: [
    CourseService
  ]

Created the component class

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

    }

Browser console error:

 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)

How to inject this service in the component?

It's impossible by design. Angular's injectables are shared (there is only one instance) for whole scope where the service has been defined. Passing different parameters in constructor for the same instance just would not make sense. If you need many instances of your service, you can create it by yourself, just do:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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