5

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?

1
  • Parameters of type string cannot be injected from the container. Just make it a local variable. Only provided services can be injected. I assume CourseServicesService is a typo above, yes? Commented Dec 14, 2017 at 22:59

1 Answer 1

7

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();
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.