aswininayak
aswininayak

Reputation: 973

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?

Upvotes: 5

Views: 1762

Answers (1)

Daniel Kucal
Daniel Kucal

Reputation: 9242

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

Upvotes: 7

Related Questions